pytest fixtures are used in python instead of classic xUnit style setup and teardown methods where a particular section of code is executed for each test case.
There are various reasons for using pytest fixtures, the major ones are below:
- pytest fixtures are implemented in a modular manner. They are easy to use and no learning curve is involved.
- Like normal functions, fixtures also have scope and lifetime. The default scope of a pytest fixture is the function scope. Apart from the function scope, the other pytest fixture scopes are – module, class, and session.
- Fixtures with function scope improves the readability and consistency in the test code. This makes code maintenance much easier.
- Pytest fixtures function are reusable and can be used for simple unit-testing as well as testing complex scenarios.
- Fixtures leverage dependency injection, the popular object-oriented programming concept. Fixture functions act as injectors and test functions that use fixtures are consumers of the fixture objects.