Conteúdo do Curso
Python Advanced Concepts
Python Advanced Concepts
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.
Obrigado pelo seu feedback!