Python模拟类实例变量

标签 python unit-testing mocking

我正在使用 Python 的 mock 库。我知道如何通过遵循 document 来模拟类实例方法。 :

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'

但是,尝试模拟类实例变量但不起作用(以下示例中的 instance.labels):

>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     instance.labels = [1, 1, 2, 2]
...     result = some_function()
...     assert result == 'the result'

基本上我希望 some_function 下的 instance.labels 获得我想要的值。有什么提示吗?

最佳答案

此版本的 some_function() 打印模拟的 labels 属性:

def some_function():
    instance = module.Foo()
    print instance.labels
    return instance.method()

我的module.py:

class Foo(object):

    labels = [5, 6, 7]

    def method(self):
        return 'some'

打补丁和你的一样:

with patch('module.Foo') as mock:
    instance = mock.return_value
    instance.method.return_value = 'the result'
    instance.labels = [1,2,3,4,5]
    result = some_function()
    assert result == 'the result

完整的控制台 session :

>>> from mock import patch
>>> import module
>>> 
>>> def some_function():
...     instance = module.Foo()
...     print instance.labels
...     return instance.method()
... 
>>> some_function()
[5, 6, 7]
'some'
>>> 
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     instance.labels = [1,2,3,4,5]
...     result = some_function()
...     assert result == 'the result'
...     
... 
[1, 2, 3, 4, 5]
>>>

对我来说,你的代码正在工作。

关于Python模拟类实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731477/

相关文章:

Python 单行 if else 语句

c++ - C++单元测试框架比较

ruby - 我可以使用 rspec 模拟来 stub 版本常量吗?

php - PHP中的单元测试数据存储

asp.net-mvc - 使用 Moq 模拟 FormsIdentity.Ticket.UserData

python - 科学 : fourier transform of a few selected frequencies

python - 在 numpy 中计算高于阈值的数组值的最快方法

python - fps - 如何将计数除以时间函数以确定 fps

unit-testing - 如何(策略)以 BDD 风格对属性进行单元测试(获取/设置)?

python - GalenRemoteWebDriver 无法连接到本地主机服务器