如果您尝试测试是否MyClass.foo()
正常工作,则不应模拟它。
模拟用于被测代码之外的任何东西;如果foo
调用另一个外部函数some_module.bar()
,那么你会模拟some_module.bar()
并给它一个分阶段的返回值:
import some_module
class MyClass(object):
def foo(self, x, y, z):
result = some_module.bar(x, y, z)
return result[0] + 2, result[1] * 2, result[2] - 2
class TestMyClass(TestCase):
@mock.patch('some_module.bar')
def test_myclass(self, mocked_bar):
mocked_bar.return_value = (10, 20, 30)
mc = MyClass()
# calling MyClass.foo returns a result based on bar()
self.assertEquals(mc.foo('spam', 'ham', 'eggs'),
(12, 40, 28))
# some_class.bar() was called with the original arguments
mocked_bar.assert_called_with('spam', 'ham', 'eggs')
Here I set mocked_bar.return_value
to what should be returned when the mocked some_module.bar()
function is called. When the code-under-test actually calls bar()
, the mock returns that value.
When you don't set a return_value
a new MagicMock()
object is returned instead, one that'll support further calls, and you can test for those calls just like on the mocked_bar
object, etc.