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


Asked By – NOOB

Can anyone explain the use of Python’s setUp and tearDown methods while writing test cases apart from that setUp is called immediately before calling the test method and tearDown is called immediately after it has been called?

Now we will see solution for issue: Explain the “setUp” and “tearDown” Python methods used in test cases


In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.

You can read more with examples here.

When a setUp() method is defined, the test runner will run that method
prior to each test. Likewise, if a tearDown() method is defined, the
test runner will invoke that method after each test.

For example you have a test that requires items to exist, or certain state – so you put these actions(creating object instances, initializing db, preparing rules and so on) into the setUp.

Also as you know each test should stop in the place where it was started – this means that we have to restore app state to it’s initial state – e.g close files, connections, removing newly created items, calling transactions callback and so on – all these steps are to be included into the tearDown.

So the idea is that test itself should contain only actions that to be performed on the test object to get the result, while setUp and tearDown are the methods to help you to leave your test code clean and flexible.

You can create a setUp and tearDown for a bunch of tests and define them in a parent class – so it would be easy for you to support such tests and update common preparations and clean ups.

If you are looking for an easy example please use the following link with example

This question is answered By – Artsiom Rudzenka

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0