我注意到 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 次通过我不知道为什么。
我做错了什么吗?我不确定,但阅读文档 docs python :
assert_called_once(*args, **kwargs)
Assert that the mock was called exactly once.
最佳答案
这是旧的,但对于其他登陆这里的人......
对于 python < 3.6,assert_called_once
不是问题,因此您实际上是在进行一个不会出错的模拟函数调用
请参阅:http://engineroom.trackmaven.com/blog/mocking-mistakes/
您可以改为检查调用次数。
关于python - 魔术模拟 assert_called_once 与 assert_called_once_with 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297549/