Skip to main content
In this article, you’ll learn how to reduce repetitive code in your bank account tests using pytest fixtures. When testing your bank account functionality, you might notice that each test requires initializing a bank account instance multiple times. For example:
When running your tests, you might see output similar to this:
Notice that every test involving the bank account starts by creating an instance:
And similarly for deposit and interest collection:
This repetitive code can become tedious when you have many tests (for example, 50 tests in a single class). Pytest fixtures help minimize this redundancy.
A fixture is simply a function that runs before your tests and sets up the necessary environment, such as creating an instance of a bank account.

Creating Fixtures

We’ll start by creating two fixtures. One fixture initializes a bank account with a zero balance and the other initializes it with a preset balance (e.g., 50). Although you can place fixtures anywhere, the best practice is to define them at the top of your test file. For example:
You can use these fixtures by adding them as parameters to your test functions. Below is an example of refactored tests using these fixtures:
When running the tests with the -s flag (which shows print statements), you’ll see that the fixture runs before your test function. For instance, the output for test_bank_default_amount will display:
This confirms that the fixture is executed prior to the test itself.

Parameterizing Fixtures and Test Scenarios

Fixtures can also be combined with pytest’s parameterization feature to test multiple scenarios. For example, you can parameterize addition test cases as shown below:
Consider a more complex test case that involves both depositing and withdrawing money. Initially, you might write:
You can further combine fixtures with parameterized data in this way:
When you run the tests, the output may look like this:
Each parameterized scenario uses the fixture to set up the test environment correctly.

Conclusion

Using pytest fixtures helps eliminate repetitive setup code across multiple tests. They not only simplify your test code for scenarios like deposit and withdrawal operations but also make it easier to manage more complex cases, such as setting up databases or external services.
By combining fixtures with parameterized test cases, you can efficiently cover a wide range of scenarios while keeping your test code concise, maintainable, and SEO-friendly.

Watch Video