python - 如何使用 nosetests 测试函数在函数内被调用

标签 python unit-testing testing nosetests

我正在尝试为项目设置一些自动单元测试。我有一些功能,作为副作用偶尔会调用另一个功能。我想编写一个单元测试来测试第二个函数是否被调用,但我很困惑。下面是伪代码示例:

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/

相关文章:

python - 计算有多少值归因于 python (3.2) 字典的键

python - 如果满足不同行中的条件,则替换数据框中的字符串

unit-testing - 如何在 Rust 代码中比较两个 JsValues 的值?

ruby-on-rails - Cucumber 是否不需要编写单元测试?

python - 将Python代码转换为C代码

python - 如何在同一台服务器上使用多个 python 虚拟环境

php - 为 PHPUnit 创建一个基本测试类并将其扩展为通用功能会导致类未找到错误

unit-testing - 了解 "test-first"和 "test-driven"之间的区别

ruby-on-rails - 运行测试时出现莫名其妙的错误

networking - 什么时候在 Weka 中使用测试和训练集?