How to a run specific code before & after each unit test in Python

11.7k views Asked by At

Following is the structure of my tests in a file.

Class
 setup
  test01
  test02
  test03
 teardown

I have a requirement to run specific code before and after each test.

For before, I could invoke that code from the setup. But for after the test, I am not able to figure how to do it. Obviously invoking the code from teardown would work for the last test, but how can I have it run for the tests in between?

1

There are 1 answers

0
Daniel Martin On

Assuming that you're properly using a class descended from unittest.TestCase, then the setUp method is run before each test, and the tearDown method is run after each test. Check the documentation. So it's completely feasible to put your code in those two methods.