【问题标题】:Python mock object instantiationPython 模拟对象实例化
【发布时间】:2016-03-04 18:55:09
【问题描述】:

使用 Python 2.7 和模拟库

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

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

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...

mylib.py:

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

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

【问题讨论】:

  • 你不就assert_called_with吗?
  • 让我编辑问题以显示一些示例代码。我尝试过 assert_call_with 但没有得到任何结果
  • 那里... @mgilson 我添加了一些示例代码。谢谢!
  • 什么是method_inside_someobject?你的意思是用test1 代替吗?为什么要重新绑定test1
  • 另外,您修补SomeObject 的方式是正确的,这意味着您肯定应该看到SomeObject.assert_called_with() 工作。您能否确保您的minimal reproducible example 正确反映了您的情况并且有效

标签: python unit-testing mocking


【解决方案1】:

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

mock_someobject.assert_called_with(arg1=val1, arg2=val2, arg3=val3)

为了说明,我已将您的 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()

mylib.py

from someobjectmodule import SomeObject

def method_to_test():
    obj = SomeObject(arg1='foo', arg2='bar', arg3='baz')
    return obj.method_inside_someobject()

someobjectmodule.py

class SomeObject(object):
    def method_inside_someobject(self):
        return 'The real thing'

并运行测试:

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

OK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多