如何使用鼻子测试测试函数中是否调用了函数 [英] How to test that a function is called within a function with nosetests

查看:85
本文介绍了如何使用鼻子测试测试函数中是否调用了函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to set up some automatic unit testing for a project. I have some functions which, as a side effect occasionally call another function. I want to write a unit test which tests that the second function gets called but I'm stumped. Below is pseudocode example:

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()-被调用?

推荐答案

您可以使用模拟模块,然后检查是否被调用.这是一个示例:

You can mock the function b using mock module and check if it was called. Here's an example:

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()

另请参阅:

  • Assert that a method was called in a Python unit test
  • Mocking a class: Mock() or patch()?

希望有帮助.

这篇关于如何使用鼻子测试测试函数中是否调用了函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆