Skip to content

Comparison of unittest.mock and Mockito Library

bhuvangupta008 edited this page Jan 31, 2018 · 1 revision
  1. In mockito you always specify concrete arguments (a call signature), and its outcome, usually a return value via thenReturn or a raised exception via thenRaise. That effectively turns function calls into constants for the time of the test. eg
from mockito import when
# stub `os.path.exists`
when(os.path).exists('/foo').thenReturn(True)
os.path.exists('/foo') # => True
os.path.exists('/bar') # -> throws unexpected invocation
  1. While in unittest.mock the MagicMock objects assumed to possess all attributes, Mockito is very picky. The test will fail if we try to access a non-existent function.

  2. In mockito you can specify return values for each set of call arguments. Using when....then the return values of a function can be specified for a specific set of arguments. But in unittest.mock, this can be implemented using side_effect by defining a separate module or by arranging the return values in a list so that whenever the first call is made irrespective of the arguments the first value is returned, with second call, the second element in the list is returned and so on.

Clone this wiki locally