How to test that a function is called within a function with nosetests

后端 未结 2 1235
Happy的楠姐
Happy的楠姐 2021-02-13 15:50

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 wh

2条回答
  •  死守一世寂寞
    2021-02-13 16:31

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

    Also see:

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

    Hope that helps.

提交回复
热议问题