且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用鼻子测试测试函数中是否调用了函数

更新时间:2022-03-21 04:57:16

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

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

希望有帮助.