我正在尝试为项目设置一些自动单元测试。我有一些功能,作为副作用偶尔会调用另一个功能。我想编写一个单元测试来测试第二个函数是否被调用,但我很困惑。下面是伪代码示例:
def a(self):
data = self.get()
if len(data) > 3500:
self.b()
# Bunch of other magic, which is easy to test.
def b(self):
serial.write("\x00\x01\x02")
如何测试 b()
- 是否被调用?
最佳答案
您可以使用 mock 模拟函数 b
模块并检查它是否被调用。这是一个例子:
import unittest
from mock import patch
def a(n):
if n > 10:
b()
def b():
print "test"
class MyTestCase(unittest.TestCase):
@patch('__main__.b')
def test_b_called(self, mock):
a(11)
self.assertTrue(mock.called)
@patch('__main__.b')
def test_b_not_called(self, mock):
a(10)
self.assertFalse(mock.called)
if __name__ == "__main__":
unittest.main()
另见:
希望对您有所帮助。
关于python - 如何使用 nosetests 测试函数在函数内被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18762293/