Python Unit Testing

In this section, you’ll learn about unit testing in Python by using the unittest modules to make your code more robust.

What you’ll learn: #

  • Write effective test cases using the unittest module
  • Run unit tests fast
  • Skip tests unconditionally and conditionally
  • Using test doubles including mocks, stubs, and fakes
  • Parameterize tests
  • Generate test coverage reports

Section 1. Introduction to unit testing in Python #

This section introduces you to the unit testing and the unittest module. After completing this section, you’ll know how to define and execute unit tests effectively.

  • What is unit testing – introduce you to the unittest testing and how to use the unittest module to perform unit tests.
  • Test fixtures – learn how to use test fixtures including setUp() and tearDown() to carry out the steps before and after test methods.
  • Skipping tests – guide you on how to skip a test method or test class.
  • Running unittest – show you various commands to run unit tests.

Section 2. assert methods #

This section covers the assert methods so that you know how to each of them more effectively.

Section 3. Test doubles #

This section introduces to you the test doubles to decouple the system under test code from the rest of the system so that code can be tested in isolation.

  • Mock – learn how to use the Mock class to mimic behaviors of another function or class.
  • patch() – show you how to use the patch() to temporarily replace an object with another object for testing.
  • Stubs – show you how to use the MagicMock class & patch() to create stubs.
  • Mocking requests module – learn how to mock the requests module to test an API call using the unittest module.

Section 4. Test coverage & Parameterized tests #

This section introduces you to the test coverage and how to define parameterized tests using the subTest() context manager.

Was this tutorial helpful ?