10

我注意到 python 的一个奇怪的assert_called_once行为assert_called_once_with。这是我真正简单的测试:

文件模块/a.py

from .b import B

class A(object):
    def __init__(self):
        self.b = B("hi")

    def call_b_hello(self):
        print(self.b.hello())

文件模块/b.py

class B(object):
    def __init__(self, string):
        print("created B")
        self.string = string;

    def hello(self):
        return self.string

这些是我的测试:

import unittest
from mock import patch
from module.a import A    

class MCVETests(unittest.TestCase):
    @patch('module.a.B')   
    def testAcallBwithMockPassCorrect(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.call_b_hello()
        a.b.hello.assert_called_once()

    @patch('module.a.B')
    def testAcallBwithMockPassCorrectWith(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.call_b_hello()
        a.b.hello.assert_called_once_with()

    @patch('module.a.B')
    def testAcallBwithMockFailCorrectWith(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.b.hello.assert_called_once_with()

    @patch('module.a.B')
    def testAcallBwithMockPassWrong(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.b.hello.assert_called_once()

if __name__ == '__main__':
    unittest.main()

如函数名称所述,我的问题是:

  • 测试 1 正确通过
  • 测试 2 正确通过
  • 测试 3 正确失败(我已删除对 b 的调用)
  • 测试 4 通过我不知道为什么。

难道我做错了什么?我不确定,但阅读文档文档 python

assert_call_once(*args, **kwargs)

断言模拟只被调用了一次。

4

1 回答 1

7

这是旧的,但对于其他登陆这里的人......

对于 python < 3.6,assert_called_once不是一件事,所以你实际上是在进行一个没有错误的模拟函数调用

请参阅:http ://engineroom.trackmaven.com/blog/mocking-mistakes/

您可以改为检查呼叫计数。

于 2019-07-17T18:44:25.297 回答