在测试后销毁Python中的mock

2 投票
2 回答
3600 浏览
提问于 2025-04-18 09:58

假设我有几个这样的测试:

class TestMyTest(unittest.TestCase):

    def SetUpClass(cls):
        cls.my_lib = MyLib()

    def my_first_test(self):
        self.my_lib.my_function = Mock(return_value=True)
        self.assertTrue(self.my_lib.run_my_function(), 'my function failed')

    def my_second_test(self):
        # Some other test that calls self.my_lib.my_function...

还有,我在MyLib里有这样的东西:

class MyLib(Object):

    def my_function(self):
        # This function does a whole bunch of stuff using an external API
        # ...

    def run_my_function(self):
        result = self.my_function()
        # Does some more stuff
        # ...

在我的第一个测试中,我把my_lib.my_function这个函数给“模拟”了,也就是说每当这个函数被调用时,它都会返回True。在这个例子里,我的断言是调用run_my_function(),这个函数也是来自同一个库,它会调用my_lib.my_function。不过,当我的第二个测试执行时,我不想调用模拟的函数,而是想调用真实的函数。所以我想我需要在运行完第一个测试后以某种方式“销毁”这个模拟,也许是在tearDown()里。那我该怎么销毁这个模拟呢?

我编辑了我的原始问题,添加了更多细节,因为看起来之前不太清楚,抱歉。

2 个回答

1

销毁这个模拟对象是没用的。你要么得重新给 self.my_lib.my_function 赋值,要么就得用另一种方式调用 Mock(return_value=True)

第一个方法似乎是Patrick的建议。

2

你可以这样做:

class TestYourLib(unittest.TestCase):

    def setUp(self):
        self.my_lib = MyLib()

    def test_my_first_test(self):
        self.my_lib.my_function = Mock(return_value=True)
        self.assertTrue(self.run_my_function(), 'my function failed')

    def test_my_second_test(self):
        # Some other test that calls self.my_lib.my_function...

然后,当下一个测试用例调用 setUp 时,Mock 就会“被销毁”,因为它超出了作用范围。

撰写回答