13 Aug 2013
When it comes to unit testing infrastructure code, mocking is sometimes difficult to avoid. In the python programming language, there are many powerful mocking libraries. are the ones we have been using so far.

Mockito is the most expressive

Mockito allows mocking in a fluent interface-ish fashion. This makes writing tests a breeze :
    
when(dog).bark().thenReturn('meow')

self.assertRaises(DogsDoNotMeowException, veterinarian.inspect, dog)
verify(dog).bark()
    
As a contrast, the Mock framework emphasizes monkey-patching, e.G.
    
dog = Mock()
dog.bark.return_value = 'meow'

self.assertRaises(DogsDoNotMeowException, veterinarian.inspect, dog)
dog.bark.assert_called_with()
    
which is definitely straightforward but not as nice to read as the above.

Readability is most important in failing tests

Passing tests are great, because it gives you confidence that your changes did not break functionality. But when they fail, you want to understand quickly what went wrong. Mockito is clearly a winner when it comes to reading the test sources, but what about error messages?

When an expected call is missing

The interesting part is when you stub and verify calls with parameters. What if a parameter is wrong or missing?

With Mockito

    
when(terminal).render(any()).thenReturn(None)

terminal.render('fooo')

verify(terminal).render('foo')
    
Guess what the error message is? (Hint: it's not useful)
    
Wanted but not invoked: render('foo')
    
Yup. That's it.

With Mock

    
terminal.render = Mock()

terminal.render('fooo')

terminal.render.assert_called_with('foo')
    
The error message is
    
AssertionError: Expected call: render('foo')
Actual call: render('fooo')
    
Mock has several other advantages over Mockito (like being able to mock open() statements very easily).
I'd gladly dismiss all these features in favor of the fluent interface style patching, but the incomplete error messages are a showstopper. If your test fails to deliver expressive messages when they are needed the most, then the test is probably more of a liability than a boon.

TLDR

I use Michael Foord's Mock and so should you.
by Maximilien Riehl

YADT an Augmented Deployment Tool
Copyright (C) 2010-2016 Immobilien Scout GmbH
Licensed under GNU GPL v3

2016-05-11 10:48:37 +0000