0
0
PyTesttesting~5 mins

unittest.mock.patch in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of unittest.mock.patch in testing?

unittest.mock.patch temporarily replaces a part of your code (like a function or object) with a mock version during a test. This helps isolate the code you want to test by controlling dependencies.

Click to reveal answer
beginner
How do you use patch as a decorator in pytest?

You add @patch('module_name.object_name') above your test function. The patched object is passed as an argument to your test, letting you control or check its behavior.

Click to reveal answer
beginner
What does patching a function mean in simple terms?

It means swapping the real function with a fake one during a test. This fake function can return controlled results or track how it was called.

Click to reveal answer
intermediate
What is the difference between patching with a decorator and patching with a context manager?

Decorator patching applies for the whole test function automatically. Context manager patching applies only inside a with block, giving more control over the patch duration.

Click to reveal answer
intermediate
Why is it important to patch the object where it is used rather than where it is defined?

You patch where the object is looked up in your code, not where it was created. This ensures your patch replaces the exact reference your code uses during the test.

Click to reveal answer
What does unittest.mock.patch do in a test?
ACompiles the code faster
BDeletes the object from the code
CReplaces a real object with a mock temporarily
DRuns the real function multiple times
How do you apply patch using a decorator in pytest?
AInside the test function with <code>with patch()</code>
B@patch('module.object') above the test function
CBy importing patch but not using it
DBy calling patch after the test runs
Where should you patch an object to ensure it works correctly?
AWhere the object is used in your code
BWhere the object is originally defined
CAnywhere in the test file
DIn a separate configuration file
What is a benefit of using patch as a context manager?
ALimits patching to a specific block of code
BAutomatically patches all tests
CMakes the patch permanent
DRuns tests faster
What can you do with the mock object passed by patch decorator?
AChange the source code of the function
BDelete the original function permanently
CRun the original function faster
DSet return values and check how it was called
Explain how unittest.mock.patch helps isolate code during testing.
Think about how you might replace a noisy part in a machine to test one part clearly.
You got /3 concepts.
    Describe the difference between patching with a decorator and patching with a context manager.
    Consider when you want the patch to start and stop.
    You got /3 concepts.