我注意到 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()
函数名称中所述的我的问题是:
我做错了什么吗?我不确定,但阅读文档 docs python:
assert_used_once(*args, **kwargs)
断言模拟仅被调用一次。
这已经很旧了,但对于其他登陆这里的人来说......
对于 python < 3.6,
assert_called_once
不是一个东西,所以你实际上是在进行一个不会出错的模拟函数调用
请参阅:嘲笑错误
您可以查看通话次数。