我注意到 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)
断言模拟只被调用了一次。