Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
SetUp and TearDown Steps | Unittest Framework
Python Advanced Concepts
course content

Contenido del Curso

Python Advanced Concepts

Python Advanced Concepts

1. Modules and Imports
2. Error Handling
3. File Handling
4. Pytest Framework
5. Unittest Framework

bookSetUp and TearDown Steps

The Four Phases of a Test:

  1. SetUp: prepare the environment. This might involve creating objects in the database, configuring system states like starting services or setting up database connections;
  2. Act: execute the function or methods to test;
  3. Assert: check and verify the outcomes against expected results;
  4. 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.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 3
some-alt