Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
knaperek Avatar asked Feb 05 '15 09:02

knaperek


People also ask

Does tearDown run after every test?

Code in a teardown() block is run upon completion of a test file, even if it exits with an error.

Where will you use setUp () and tearDown () methods?

Prepare and Tear Down State for a Test Class XCTest runs setUp() once before the test class begins. If you need to clean up temporary files or capture any data that you want to analyze after the test class is complete, use the tearDown() class method on XCTestCase .

What does a unittest assert do?

The assert section ensures that the code behaves as expected. Assertions replace us humans in checking that the software does what it should. They express requirements that the unit under test is expected to meet.

What is tearDown in unit testing?

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.


2 Answers

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.

like image 147
El Bert Avatar answered Oct 12 '22 23:10

El Bert


Mmh i have never seen this before. Personally i wouldn't do it because it doesn't belong there. I would do it via a decorator that does the asserts for you at the end. Then just decorate the test functions that you do want to have these asserts.

For an excellent introduction to python decorators see the answers to this question

like image 34
Salo Avatar answered Oct 13 '22 00:10

Salo