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?
Code in a teardown() block is run upon completion of a test file, even if it exits with an error.
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 .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With