31

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?

0

2 Answers 2

33

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How can we mock when get_complex_data_structure() has some parameters and called two times returning two different values foo1 and foo2 ? Above given solution will generate same mocked values for foo1 and foo2
@chintan-p-bhatt: then set Mock.side_effect, either to an iterable (and Python will use the next value from that iterable for each call), or a function; a function is given the same arguments so you can return a value based on those.
@chintan-p-bhatt: You can't use multiple lines in comments, or code blocks; only ` single backticks work. You don't need to show me how you managed to get it to work, here are other answers I gave on mocking that use .side_effect that you could reference. If you have a new question, you could create a new post on that.
11

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.