Python Mocking with unitest.mock 2: Difference between revisions
Jump to navigation
Jump to search
Line 8: | Line 8: | ||
The general approach is to replace at runtime the real method instance associated with the class instance to be tested with a <code>Mock</code> instance, configured to simulate various behaviors of the real method. | The general approach is to replace at runtime the real method instance associated with the class instance to be tested with a <code>Mock</code> instance, configured to simulate various behaviors of the real method. | ||
Assuming | Assuming that our dependency to test with is <code>SomeClass</code>, and this class has a <code>some_method(nuance: str)</code> whose behavior we want to mock during testing, the initial implementation of the class and method could be: | ||
<syntaxhighlight lang='py'> | |||
class SomeClass: | |||
def __init__(self, color: str): | |||
self._color = color | |||
def some_method(self, nuance: str) -> str: | |||
return f'{nuance} {self._color}'.upper() | |||
</syntaxhighlight> | |||
==Simulating a Particular Return Value Irrespective of the Arguments it was Called With== | ==Simulating a Particular Return Value Irrespective of the Arguments it was Called With== |
Revision as of 23:00, 1 June 2023
Internal
Mocking a Method
The general approach is to replace at runtime the real method instance associated with the class instance to be tested with a Mock
instance, configured to simulate various behaviors of the real method.
Assuming that our dependency to test with is SomeClass
, and this class has a some_method(nuance: str)
whose behavior we want to mock during testing, the initial implementation of the class and method could be:
class SomeClass:
def __init__(self, color: str):
self._color = color
def some_method(self, nuance: str) -> str:
return f'{nuance} {self._color}'.upper()