单元测试时如何从模拟实例方法访问对象实例?

2024-04-19 22:59:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面写着foo_obj = ????的代码中,如何获得对Foo对象实例的引用,或者有什么更好的方法?你知道吗

class Foo(object):

    def __init__(self):
        self.hello = "Hey!"

    def bar(self):
        return self.hello + " How's it going?"

def side_effect_foo_bar(*args, **kwargs):
    foo_obj = ????
    return foo_obj.hello + " What's up?"

class TestFoo(unittest.TestCase):

    @patch.object(Foo, 'bar')
    def test_bar(self, mocked_bar):
        mocked_bar.side_effect = side_effect_foo_bar
        foo = Foo()
        self.assertTrue(foo.bar() == "Hey! What's up?")

Tags: selfobjhelloreturnobjectfoodefbar
1条回答
网友
1楼 · 发布于 2024-04-19 22:59:16

多亏了这个:

http://mock.readthedocs.org/en/latest/examples.html#mocking-unbound-methods

诀窍是在@patch.object(Foo, 'bar', autospec=True)中添加autospec=True。你知道吗

class Foo(object):

    def __init__(self):
        self.hello = "Hey!"

    def bar(self):
        return self.hello + " How's it going?"

def side_effect_foo_bar(*args, **kwargs):
    return args[0].hello + " What's up?"

class TestFoo(unittest.TestCase):

    @patch.object(Foo, 'bar', autospec=True)
    def test_bar(self, mocked_bar):
        mocked_bar.side_effect = side_effect_foo_bar
        foo = Foo()
        self.assertTrue(foo.bar() == "Hey! What's up?")

相关问题 更多 >