Skip to content Skip to sidebar Skip to footer

Python Mock Library - Patching Classes While Unit Testing

I cannot understand how mock patch works and if does it able to solve my problem. I have 3 files: communication with external interface (a.py), business logic (b.py) and tests (tes

Solution 1:

As stated in Where to patch:

patch works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.

In your example, the code using the object you want patched is in module b. When you call patch, the class has already been imported in module b, so patching a will have no effect on b. You need instead to path the object in b:

@mock.patch('src.tmp.mocks.b.SomeProductionClassINeedPatch')

This will give you the expected result, the first call from b is unpatched, while the second call from test used the mock object:

# python test.py
False<some feature withexternal service>True<test>-True

Post a Comment for "Python Mock Library - Patching Classes While Unit Testing"