Let's say I have a class like this.
class SomeProductionProcess(CustomCachedSingleTon):
def loaddata():
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
Now at test time I want to change the logic inside the loaddata()
method. It would be a simple custom logic that doesn't process large data.
How do we supply custom implementation of loaddata()
at testtime using Python Mock UnitTest framework?
To easily mock out a class method with a structured return_value, can use
unittest.mock.Mock
.EDIT:
Since you want to mock out the method with a custom implementation, you could just create a custom mock method object and swap out the original method at testing runtime.
Here is a simple way to do it using mock
I'd recommend using
pytest
instead of theunittest
module if you're able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get withunittest.TestCase
-style tests.Lets say you have a module named awesome.py and in it, you had:
Then your unittest where you mock
loaddata
could look like this:Or it could look like this:
Now when you run your test,
loaddata
wont take 30 seconds for those test cases.