I am using mock with Python and was wondering which of those two approaches is better (read: more pythonic).
Method one: Just create a mock object and use that. The code looks like:
def test_one (self):
mock = Mock()
mock.method.return_value = True
# This should call mock.method and check the result.
self.sut.something(mock)
self.assertTrue(mock.method.called)
Method two: Use patch to create a mock. The code looks like:
@patch("MyClass")
def test_two (self, mock):
instance = mock.return_value
instance.method.return_value = True
# This should call mock.method and check the result.
self.sut.something(instance)
self.assertTrue(instance.method.called)
Both methods do the same thing. I am unsure of the differences.
Could anyone enlighten me?
mock.patchis a very very different critter thanmock.Mock.patchreplaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:patchreplacesMyClassin a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.mock.patchis usually used when you are testing something that creates a new instance of a class inside of the test.mock.Mockinstances are clearer and are preferred. If yourself.sut.somethingmethod created an instance ofMyClassinstead of receiving an instance as a parameter, thenmock.patchwould be appropriate here.