【问题标题】:Assert whether a function is being called inside another function断言一个函数是否在另一个函数内部被调用
【发布时间】:2022-01-17 06:23:58
【问题描述】:

我有 2 个函数,只有当传递的参数为 True 时才会调用另一个函数。

def func1(para1 = True):
       // Some lines of code
       if para1 == True:
               func2()

def func2():
       // Some lines of code

现在,我正在尝试创建一个单元测试来检查嵌套函数 func2 是否被调用(当传递给 func1 的参数为真时)。我在网上查了一下,发现了一些与 Mock() 相关的东西,但不明白如何用于这个特定的测试用例。我该如何继续?

【问题讨论】:

    标签: python-3.x function unit-testing testing


    【解决方案1】:

    example.py:

    def func1(para1=True):
        if para1 == True:
            func2()
    
    
    def func2():
        pass
    

    test_example.py:

    from unittest import TestCase
    import unittest
    from unittest.mock import patch
    from example import func1
    
    
    class TestExample(TestCase):
        @patch('example.func2')
        def test_func1__should_call_func2(self, mock_func2):
            func1()
            mock_func2.assert_called_once()
    
        @patch('example.func2')
        def test_func1__should_not_call_func2(self, mock_func2):
            func1(False)
            mock_func2.assert_not_called()
    
    
    if __name__ == '__main__':
        unittest.main()
    

    测试结果:

    ..
    ----------------------------------------------------------------------
    Ran 2 tests in 0.001s
    
    OK
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 2011-05-30
      • 2017-05-08
      • 1970-01-01
      相关资源
      最近更新 更多