Contenido del Curso
Python Advanced Concepts
Python Advanced Concepts
SetUp and TearDown Steps
The Four Phases of a Test:
- SetUp: prepare the environment. This might involve creating objects in the database, configuring system states like starting services or setting up database connections;
- Act: execute the function or methods to test;
- Assert: check and verify the outcomes against expected results;
- TearDown: clean up after each test. This ensures that any changes to the environment do not affect subsequent tests.
SetUp and tearDown are optional phases.
Implementing SetUp and TearDown
The setUp and tearDown methods in Unittest are instance methods called before and after each test method, respectively.
Let's consider a Book
class with a custom __repr__
and sale
methods.
The next step, we'll define the test cases inside TestBook
class.
After the test_sale
case passed, the number of books was reset to the original value for the test_book_repr
because the setUp method runs before each test.
SetUp and tearDown at the method level ensure that each test runs in a clean environment, making tests predictable and independent.
Implementing SetUpClass and TearDownClass
These are class methods that run once for the whole class, at the beginning and end of the test suite.
SetUp and tearDown at the class level reduce the overhead of preparing and cleaning up resources that are expensive to create and destroy.
¡Gracias por tus comentarios!