Introduction to Unit Testing in Python using unittest framework Part 2
In part 1 we learned how to unit test Python code using unittest framework. In this tutorial we’re going to improve on our test class by introducing fixtures. For us to understand fixtures we must point out the problem we’re solving.
Let’s have a look at our test class.
If you look at line 12, BMW is included in expected result of our second test. Actually the expected result should only have Toyota after Nissan is removed. This is because all tests should work with our original list as defined on line 5. But by the time second test is executed the list has already been modified by the first test. Let’s experiment by modifying the expected result of the second test as follows (Update line 12):
expected=['Toyota']
Re-run the tests. The second test will fail as shown on the figure below.
The test expects the list to contain BMW since it was modified by the first test. Thus for the second test to run we must work with the modified list. This might produce undesirable results since the tests that are executed first can interfere with the provided dataset or test conditions. We can sum up the discussion as follows:
Each test unit must be fully independent. Each test must be able to run alone, and also within the test suite, regardless of the order that they are called. The implication of this rule is that each test must be loaded with a fresh dataset and may have to do some cleanup afterwards. This is usually handled by setUp() and tearDown() methods.
To solve our problem we’ve to use fixtures.
A test must run in a known state and then return it to its original state when the test is complete. This known state is called the fixture of the test.
Fixtures are managed using setUp() and tearDown() methods. The setup method prepares test data or preconditions e.g. a database connection or dataset as we’ve previously seen with the list of car makes. On the hand teardown method restores the fixture to a known or initial state e.g. cleaning up database connection.
The main advantage of a test fixture is that it allows for tests to be repeatable since each test is always starting with the same setup. That’s to say test fixtures preconfigure tests into a known initial state instead of working with whatever was left from a previous test run.
Let’s now update our test so that all the tests can use the same list. See code snippet below:
Re-run the tests. All tests must pass this time.
Remember to clap and follow me for more testing tutorials.