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

Conteúdo do Curso

Python Advanced Concepts

Python Advanced Concepts

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

book
Mocking in Details

In the previous chapter, we saw the importance of using Mock in testing. Now, let's take a closer look at the different capabilities and clarify any aspects that were unclear.

Introduction to MagicMock

MagicMock is an incredibly versatile implementation of Mock that supports magic methods. You can use it to mimic the behavior of complex objects in your tests as we saw in previous chapter.

In this example, MagicMock is used to simulate the get_account_balance method, which would typically retrieve data from a database.

Using mock.patch

@mock.patch is used for temporarily replacing the real implementations of objects in your code.

Imagine a function that checks user credentials against a database. You can use mock.patch to avoid hitting the actual database:

Mocking with Context Manager

At times, it's preferable to employ patch() as a context manager instead of a decorator, particularly when:

  • you need to mock an object for just a portion of the test;
  • or when excessive use of decorators or parameters is reducing the clarity of your tests.

Pytest Monkey Patch

The monkeypatch fixture in Pytest lets you temporarily modify classes, modules, or environments during a test.

The monkeypatch fixture allows you to safely modify and manage the environment during the test without causing side effects outside the test scope.

1. Which of the following code snippets correctly mocks the get_balance method to return 500?
2. What does the following test check?
Which of the following code snippets correctly mocks the get_balance method to return 500?

Which of the following code snippets correctly mocks the get_balance method to return 500?

Selecione a resposta correta

What does the following test check?

What does the following test check?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 5
We're sorry to hear that something went wrong. What happened?
some-alt