Search code examples
pythontestcaseunit-testing

Is it OK to assert in unittest tearDown method?


I have a TestCase with multiple tests and need to assert a few conditions (the same for every test) at the end of each test. Is it OK to add these assertions to the tearDown() method, or is it a bad habit since they're not "cleaning" anything?

What would be the right way of doing this?


Solution

  • Asserting something in your tearDown means that you need to be careful that all the cleaning is done before the actual asserting otherwise the cleaning code may not be called if the assert statement fails and raises.

    If the assert is just one line it may be OK to have it in every test methods, if it is more than that having a specific method would be a possibility- that method should not be a test of its own i.e. not recognized as a test by your test framework. Using a method decorator or class decorator may also be an alternative.

    Overall the idea is that tearDown shouldn't do any testing and that explicit is better than implicit.