首页 > 解决方案 > 如何在保持自定义返回值的同时在模拟类上调用 assert_call_with?

问题描述

假设我想测试一个类B并检查它的成员函数foo是否正确实例化并调用了一个类A并调用了bar它的方法。当我模拟A执行此操作时,如何检查它是否被正确调用,同时确保该方法仍按预期返回其参数B

这是我的尝试:

class B():
    def __init__(self):
        pass

    def foo(self, arg):
        a = A()
        res = a.bar(arg)
        print(f'foo called with {arg} and returned {res}')
        assert res == arg
        
        return res

class A():
    def bar(self, arg):
        return arg

import unittest
import unittest.mock

class MockA:
    @unittest.mock.create_autospec
    def bar(self, arg):
        return arg

@unittest.mock.patch("__main__.A", new=MockA)
class MyTestCase(unittest.TestCase):

    def test_case_1(self):
        x = B().foo(1)
        A.bar.assert_called_with(1)

    def test_case_2(self):
        x = B().foo(2)
        A.bar.assert_called_with(2)

    def test_case_3(self):
        x = B().foo(3)
        A.bar.assert_called_with(3)

MyTestCase().test_case_1()

这会因断言错误而失败,因为resis <MagicMock name='mock()' id='140545715265664'>。为什么autospec装饰器MockA.bar会以这种方式忽略返回值?

标签: pythonmockingpython-unittest

解决方案


推荐阅读