我很难模拟一个对象的实例。
我想编写一个单元测试来测试使用类实例的“my_func”函数。我知道如何模拟类函数,但是,我不知道如何模拟类(对象)本身的实例(不是函数)。
在我的模块文件中:
# my_module.py
import fancypackage1
import fancypackage2
def my_func():
x = fancypackage1.SomeClass.somefunction() # I know how to mock this
myclient = fancypackage2.Client() # I don't know how to mock this
myresult = do_something(myclient, x) # I know how to mock this
return myresult
在我的测试文件中:
# test_my_module.py
import pytest
import mock
import fancypackage1
import fancypackage2
from my_module import my_func
def test_my_func(mocker):
mock_someclass_somefunction = mocker.patch('my_module.fancypackage1.SomeClass.somefunction')
mock_someclass_somefunction.return_value = 'hello'
mock_client = mocker.patch.object(fancypackage2.Client, '__init__') # TypeError: __init__() should return None, not 'MagicMock'
mock_do_something = mocker.patch('my_module.do_something')
my_func()
mock_do_something.assert_called_with(mock_client, 'hello')
因为我不知道如何模拟一个类的实例,但我知道如何模拟一个类方法,所以我认为对于类的实例,使用构造函数可能会起作用 - 所以我使用了init,但是不幸的是,这对我不起作用,我收到一个错误:
E TypeError: __init__() should return None, not 'MagicMock'
在上面没有工作后,我尝试通过一个定制的夹具:
@pytest.fixture def client_constructor_mock(): my_client = fancypackage2.Client() return my_client def test_my_func(mocker, client_constructor_mock): mock_someclass_somefunction = mocker.patch('my_module.fancypackage1.SomeClass.somefunction') mock_someclass_somefunction.return_value = 'hello' mock_client = client_constructor_mock mock_do_something = mocker.patch('my_module.do_something') my_func() mock_do_something.assert_called_with(mock_client, 'hello')
不幸的是,这也不起作用。我得到的错误:
> mock_do_something.assert_called_with(mock_client, 'hello')
E AssertionError: Expected call: do_something(<fancypackage2.Client object at 0x000001E6896A69C8>, 'hello')
E Actual call: do_something(<fancypackage2.Client object at 0x000001E689721488>, 'hello')
它告诉我类 Client 有两个不同的对象,这就是错误。
我在这里不知所措,如何确保正确模拟我的客户?很感谢任何形式的帮助。