Question
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
- self.sut.something(mock) # This should called mock.method and checks the result.
- self.assertTrue(mock.method.called)
- @patch("MyClass")
- def test_two (self, mock):
- instance = mock.return_value
- instance.method.return_value = True
- self.sut.something(instance) # This should called mock.method and checks the result.
- self.assertTrue(instance.method.called)
Could anyone enlighten me?
How-To
mock.patch is a very very different critter than mock.Mock. patch replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:
patch replaces MyClz in 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.patch is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock instances are clearer and are preferred. If your self.sut.something method created an instance of MyClz instead of receiving an instance as a parameter, then mock.patch would be appropriate here.
沒有留言:
張貼留言