Python模拟对象实例化

Jav*_* C. 4 python unit-testing mocking

使用Python 2.7和模拟库

如何使用模拟测试是否已使用某些特定参数初始化某些修补对象?

这里有一些示例代码和伪代码:

unittest.py:

import mock
@mock.patch('mylib.SomeObject')
def test_mytest(self, mock_someobject):
  test1 = mock_someobject.return_value
  test1 = method_inside_someobject.side_effect = ['something']

  mylib.method_to_test()

  # How can I assert that method_to_test instanced SomeObject with certain arguments?
  # I further test things with that method_inside_someobject call, no problems there...
Run Code Online (Sandbox Code Playgroud)

mylib.py:

from someobjectmodule import SomeObject
def method_to_test():
  obj = SomeObject(arg1=val1, arg2=val2, arg3=val3)
  obj.method_inside_someobject()
Run Code Online (Sandbox Code Playgroud)

那么,如何测试SomeObject的实例是arg1 = val1,arg2 = val2,arg3 = val3?

Mar*_*ers 7

如果用模拟替换了类,则创建实例只是另一个调用。断言正确的参数已传递给该调用,例如,使用mock.assert_called_with()

mock_someobject.assert_called_with(arg1=val1, arg2=val2, arg3=val3)
Run Code Online (Sandbox Code Playgroud)

为了说明,我将您的MCVE更新为一个有效的示例:

test.py

import mock
import unittest

import mylib


class TestMyLib(unittest.TestCase):
    @mock.patch('mylib.SomeObject')
    def test_mytest(self, mock_someobject):
        mock_instance = mock_someobject.return_value
        mock_instance.method_inside_someobject.side_effect = ['something']

        retval = mylib.method_to_test()

        mock_someobject.assert_called_with(arg1='foo', arg2='bar', arg3='baz')
        self.assertEqual(retval, 'something')


if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

mylib.py

from someobjectmodule import SomeObject

def method_to_test():
    obj = SomeObject(arg1='foo', arg2='bar', arg3='baz')
    return obj.method_inside_someobject()
Run Code Online (Sandbox Code Playgroud)

someobjectmodule.py

class SomeObject(object):
    def method_inside_someobject(self):
        return 'The real thing'
Run Code Online (Sandbox Code Playgroud)

并运行测试:

$ python test.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Run Code Online (Sandbox Code Playgroud)