1. Fixtures in unittest
Now you will learn about the fixtures in unittest.
2. Fixtures recap
Let's start with what we already know about fixtures in pytest. A fixture is a prepared environment that can be used for a test execution. We need it to make the fixture code reusable and to make the test setup easier by isolating the preparation code from the test itself. Fixture setup is a process of preparing the environment and setting up resources. Fixture teardown is a process of cleaning up the resources that were allocated. An example of a fixture is preparing the food for a picnic and cleaning up at the end after ourselves.
3. Fixtures in the unittest library
It's similar in unittest. A unittest test fixture is a preparation needed to perform one or more tests. The definitions of setup and teardown are the same. The main difference of unittest is that setup and teardown are methods that belong to the test case class and not just standalone functions.
4. Example code
To create a fixture for a unittest Test Case, we have to override the "setUp" and the "tearDown" methods. Python will execute all of the instructions inside of the "setUp" method before running the test function. Then, Python will execute all of the test methods. And finally, it will call the "tearDown" method to clean the environment.
For example, in this code snippet, the setup is the initialization of the list "li". And the teardown is making the list empty by calling the "clear" method. The test function uses "assert in" and "assert not in" to check the membership of certain elements in the list.
5. Capital U and capital D
Note, it is very important to create methods with the exact showed names: "setUp" with a capital "U" and "tearDown" with a capital "D". Otherwise, unittest will not recognize the method as a fixture, and it will result into an error.
6. Example output
Now, let's run the code and analyze its output. As we can see, it works. And the results look exactly the same as without any fixtures involved.
7. Incorrectly named methods
Now, let's try to name the setup method incorrectly. For example, let's name it "set underscore up". This time, the test resulted in two errors. They both tell us that the test class has no attribute "li". That is exactly the list that we wanted to initialize on the setup, but it did not work because we named the setup method incorrectly.
8. Summary
In this video, we learned about fixtures in unittest. Fixture is the preparation needed to perform one or more tests. To create a fixture within the unittest framework, we have to implement the "setUp" and "tearDown" methods. The setup method will be called before any of the test functions and the teardown after them.
9. Let's practice!
Now you are familiar with how to create fixtures in unittest. So try to create some tests using them.