How to properly use mock in python with unittest setUp

前端 未结 5 2156
北荒
北荒 2020-12-08 00:15

In my attempt to learn TDD, trying to learn unit testing and using mock with python. Slowly getting the hang of it, but unsure if I\'m doing this correctly. Forewarned: I\

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 00:25

    I'd like to point out a variation of the accepted answer in which a new argument is passed to the patch() decorator:

    from unittest.mock import patch, Mock
    
    MockSomeClass = Mock()
    
    @patch('mymodule.SomeClass', new=MockSomeClass)
    class MyTest(TestCase):
        def test_one(self):
            # Do your test here
    

    Note that in this case, it is no longer necessary to add the second argument, MockSomeClass, to every test method, which can save a lot of code repetition.

    An explanation of this can be found at https://docs.python.org/3/library/unittest.mock.html#patch:

    If patch() is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function.

    The answers above all omit new, but it can be convenient to include it.

提交回复
热议问题