且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 python 单元测试中集成模拟和补丁

更新时间:2023-01-18 16:06:57

好的,试着给你一个想法.在测试中,您为测试创建了一个伪造的 addCookie 方法,但您仅使用它来检查 addCookie 是如何被调用的.因此,例如,您可以重写测试 3 和 4:

Ok, trying to give you an idea. In the tests, you have created a fake addCookie method for your tests, but you only use it to check how addCookie has been called. So, for example, your test 3 and 4 you could rewrite:

   def test_03_set_nonce(self):
        request = mock.Mock()
        self.web_session.set_nonce(request)
        # we only need to know that it was called once
        request.addCookie.assert_called_once()

   def test_04_get_valid_nonce(self):
        request = mock.Mock()
        web_session = WebViewLincSession()
        web_session.set_nonce(request)
        web_session.set_nonce(request)
        # check that addCookie it has been called twice
        self.assertEqual(2, request.addCookie.call_count)
        
        valid_nonce = web_session.get_valid_nonce()
        ... # the rest is not dependent on mocks

在其他测试中,您可能还需要检查调用中使用的参数.您始终必须定义您实际想要测试的内容,然后设置您的模拟,以便仅测试该功能.

In other tests, you may have also to check the arguments used in the calls. You always have to define what you are actually want to test, and then setup your mocks so that only that functionality is tested.

另请注意,在某些情况下,像您所做的那样使用额外的模拟类可能是有意义的 - 如果这对您最有效,那没有任何问题.

Note also that in some cases it may make sense to use extra mock classes like you have done - there is nothing wrong with that, if that works best for you.