模拟通过实例使用的类方法

时间:2012-03-15 21:52:49

标签: python unit-testing mocking

我正在尝试使用模拟修补类方法in the documentation。 Mock对象本身工作正常,但它的方法不能:例如,即使call_count类对象的method_calls属性,它们的属性如Mock也不会更新。更重要的是,他们的return_value属性会被忽略:

class Lib:
    """In my actual program, a module that I import"""
    def method(self):
        return "real"

class User:
    """The class I want to test"""
    def run(self):
        l = Lib()
        return l.method()

with patch("__main__.Lib") as mock:
    #mock.return_value = "bla" # This works
    mock.method.return_value = "mock"
    u = User()
    print(u.run())

>>> 
mock
<MagicMock name='Lib().method()' id='39868624'>

我在这里做错了什么?

编辑:通过构造函数传递类Mock也不起作用,因此这与patch函数无关。

3 个答案:

答案 0 :(得分:16)

我发现了我的错误:为了配置我的模拟实例的方法,我必须使用mock().method而不是mock.method

class Lib:
    """In my actual program, a module that I import"""
    def method(self):
        return "real"

class User:
    """The class I want to test"""
    def run(self):
        l = Lib()
        return l.method()

with patch("__main__.Lib") as mock:
    #mock.return_value = "bla" # This works
    mock().method.return_value = "mock"
    u = User()
    print(u.run())

答案 1 :(得分:1)

from mock import *

class Lib:
    """In my actual program, a module that I import"""
    def method(self):
        return "real"

class User:
    """The class I want to test"""
    def run(self, m):

        return m.method()

with patch("__main__.Lib") as mock:
    #mock.return_value = "bla" # This works
    mock.method.return_value = "mock"

    print User().run(mock)

答案 2 :(得分:1)

我模仿这样的类方法:

def raiser(*args, **kwargs):
    raise forms.ValidationError('foo')
with mock.patch.object(mylib.Commands, 'my_class_method', classmethod(raiser)):
    response=self.admin_client.get(url, data=dict(term='+1000'))