0
0
PyTesttesting~5 mins

Mock and MagicMock in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of Mock in pytest?

Mock is used to replace parts of your system under test with mock objects. It helps simulate and control the behavior of dependencies so you can test your code in isolation.

Click to reveal answer
intermediate
How does MagicMock differ from Mock?
<p><code>MagicMock</code> is a subclass of <code>Mock</code> that has default implementations for most magic methods like <code>__len__</code>, <code>__getitem__</code>, and others. It is useful when you need to mock objects that use these special methods.</p>
Click to reveal answer
beginner
How do you check if a mocked method was called in pytest?

You use the assert_called() or assert_called_once() methods on the mock object to verify if it was called during the test.

Click to reveal answer
beginner
What does mock.return_value do?

mock.return_value sets the value that the mock object returns when called. This lets you control the output of the mocked function or method.

Click to reveal answer
beginner
Why use mocking in unit tests?

Mocking helps isolate the code you want to test by replacing external dependencies. This makes tests faster, more reliable, and focused on the specific code behavior.

Click to reveal answer
Which of the following is true about MagicMock?
AIt only works with classes, not functions.
BIt automatically mocks magic methods like <code>__len__</code> and <code>__getitem__</code>.
CIt is slower than <code>Mock</code> and should be avoided.
DIt cannot mock methods that start with an underscore.
How do you set a mock to return a specific value when called?
Amock.return_value = value
Bmock.call_value = value
Cmock.set_return(value)
Dmock.value = return
What does mock.assert_called_once() check?
AThe mock was never called.
BThe mock was called at least once.
CThe mock was called exactly once.
DThe mock was called more than once.
Why is mocking useful in unit testing?
AIt replaces dependencies to isolate the code under test.
BIt automatically fixes bugs in the code.
CIt makes tests slower but more accurate.
DIt removes the need for assertions.
Which method would you use to check if a mock was called with specific arguments?
Amock.called_with_args()
Bmock.check_args()
Cmock.verify_call()
Dmock.assert_called_with()
Explain how you would use Mock and MagicMock in a pytest unit test.
Think about isolating code and controlling behavior of dependencies.
You got /4 concepts.
    Describe the benefits of using mocking in software testing.
    Consider how mocking affects test speed and reliability.
    You got /4 concepts.