How to properly use mock in python with unittest setUp

前端 未结 5 2161
北荒
北荒 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:19

    If you have many patches to apply and you want them to apply to things initialised in the setUp methods too try this:

    def setUp(self):
        self.patches = {
            "sut.BaseTestRunner._acquire_slot": mock.Mock(),
            "sut.GetResource": mock.Mock(spec=GetResource),
            "sut.models": mock.Mock(spec=models),
            "sut.DbApi": make_db_api_mock()
        }
    
        self.applied_patches = [mock.patch(patch, data) for patch, data in self.patches.items()]
        [patch.apply for patch in self.applied_patches]
        .
        . rest of setup
        .
    
    
    def tearDown(self):
        patch.stopall()
    

提交回复
热议问题