在tes之后销毁Python中的mock

2024-10-03 13:28:09 发布

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

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

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中有这样的东西:

^{pr2}$

在我的初试中,我在嘲笑我_lib.my_函数并在执行函数时返回True。在这个例子中,我的断言调用run_my_function(),这是来自同一个库的另一个函数,它调用my_lib.my_函数. 但是当我的第二个测试执行时,我不希望调用模拟函数,而是调用真正的函数。所以我想我需要在运行完我的unu first_测试之后以某种方式销毁mock,可能是在tearDown()期间。我该如何摧毁这个模拟?在

我修改了我原来的问题,增加了更多的细节,因为看起来不太清楚,很抱歉。在


Tags: 函数runtestselftruemylibdef
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。在

破坏模拟是不行的。您要么重新分配self.my_lib.my_function,要么以不同的方式调用Mock(return_value=True)。在

首先是帕特里克的建议。在

相关问题 更多 >