Python模拟对象实例化 [英] Python mock object instantiation

查看:109
本文介绍了Python模拟对象实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python 2.7和模拟库

Using Python 2.7, and mock library

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

How can I test that certain patched object has been initialized with some specific arguments using mock?

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

Here some sample code and pseudo-code:

unittest.py:

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实例化的?

So, how can I test SomeObject was instanced with arg1=val1, arg2=val2, arg3=val3?

推荐答案

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

If you replaced a class with a mock, creating an instance is just another call. Assert that the right parameters have been passed to that call, for example, with mock.assert_called_with():

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

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

To illustrate, I've updated your MCVE to a working example:

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

这篇关于Python模拟对象实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆