Explain the “setUp” and “tearDown” Python methods used in test cases

后端 未结 3 1981
一生所求
一生所求 2021-01-30 09:47

Can anyone explain the use of Python\'s setUp and tearDown methods while writing test cases apart from that setUp is called immediately be

3条回答
  •  孤城傲影
    2021-01-30 10:47

    You can use these to factor out code common to all tests in the test suite.

    If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

    You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

    If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

    For example:

    class TurretTest(unittest.TestCase):
    
        def setUp(self):
            self.turret_factory = TurretFactory()
            self.turret = self.turret_factory.CreateTurret()
    
        def test_turret_is_on_by_default(self):
            self.assertEquals(True, self.turret.is_on())
    
        def test_turret_turns_can_be_turned_off(self):
            self.turret.turn_off()
            self.assertEquals(False, self.turret.is_on())
    

提交回复
热议问题