python - 如何测试python中的方法中是否调用了另一个类方法?
问题描述
我有以下结构:
ClassB():
def foo():
Class A():
def __init__(self, B):
#some initialisations
def method1():
#complex logic
B.foo()
我正在尝试编写一个单元测试方法 1 并想测试 foo 是否被调用一次。我怎样才能做到这一点?我应该嘲笑什么?
解决方案
已编辑
根据OP提供的进一步信息,对答案进行了返工。
代码
下面的代码已经在CentOS 8上用Python3.8.3本地测试过,运行python3 -m unittest
看看测试结果。
功能代码(sub.py):
class B():
def foo(self):
pass
class A():
def __init__(self, B):
self.b = B
def method1(self):
self.b.foo()
测试代码(test.py):
from unittest import TestCase
from unittest.mock import patch
from sub import A, B
class Test(TestCase):
def test_A(self):
with patch('sub.B.foo') as mock_foo:
a = A(B)
a.method1()
mock_foo.assert_called_once()
基本上,测试代码会尝试模拟该B.foo
方法并检查该方法是否在被调用时A.method1
被调用过一次。
测试说明
a = A(B)
线路不调用B.foo
a.method1()
线路呼叫B.foo
总共B.foo
只调用一次,所以mock_foo.assert_called_once()
会通过。如果上述任何参数被证明无效,则断言将失败。如果您只需要检查B.foo
是否已至少调用一次,请mock_foo.assert_called()
改用。
关于 mock 系统的详细信息,我建议阅读官方文档。
推荐阅读
- android - 图像随不同设备改变位置
- python - Python正则表达式替换字符串的一部分
- ios - 使用 UICollectionViewFlowLayout 的 UICollectionView 使单元格居中和未对齐
- scala - 在 Scala 中导入对象的方法
- typescript - 避免在 TypeScript 数组构造中重复方法调用
- java - 子程序总是返回 -1 值,我该如何重新排列以使其发挥作用?
- tensorflow - 在 keras.sequential 模型中使用 keras.layers.Add()
- javascript - Javascript返回数组中最高值的所有索引
- python - 通过位于不同服务器中的同一文件进行 Python 文件迭代,更改 5 个参数
- scala - 识别窗口上的列的重复值(Scala)