For unit testing, I want to mock a variable inside a function, such as:
def function_to_test(self):
foo = get_complex_data_structure() # Do not test this
do_work(foo) # Test this
I my unit test, I don't want to be dependent on what get_complex_data_structure()
would return, and therefore want to set the value of foo manually.
How do I accomplish this? Is this the place for @patch.object
?
If you need to mock a global variable for all of your tests, you can use the setupFiles in your Jest config and point it to a file that mocks the necessary variables. This way, you will have the global variable mocked globally for all test suites.
With a module variable you can can either set the value directly or use mock.
patch() uses this parameter to pass the mocked object into your test. From there, you can modify the mock or make assertions as necessary. Technical Detail: patch() returns an instance of MagicMock , which is a Mock subclass. MagicMock is useful because it implements most magic methods for you, such as .
Just use @patch()
to mock out get_complex_data_structure()
:
@patch('module_under_test.get_complex_data_structure')
def test_function_to_test(self, mocked_function):
foo_mock = mocked_function.return_value
When the test function then calls get_complex_data_structure()
a mock object is returned and stored in the local name foo
; the very same object that mocked_function.return_value
references in the above test; you can use that value to test if do_work()
got passed the right object, for example.
Assuming that get_complex_data_structure is a function1, you can just patch it using any of the various mock.patch utilities:
with mock.patch.object(the_module, 'get_complex_data_structure', return_value=something)
val = function_to_test()
...
they can be used as decorators or context managers or explicitly started and stopped using the start
and stop
methods.2
1If it's not a function, you can always factor that code out into a simple utility function which returns the complex data-structure
2There are a million ways to use mocks -- It pays to read the docs to figure out all the ways that you can set the return value, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With