Question

I have to mock a method shown below:

Actual python method

import json
def some_method(self):
    output_one = json.loads(varone)
    output_two = json.loads(vartwo)

Test Method

import json
self.stubs = stubout.StubOutForTesting()
self.stubs.Set(json, "loads", lambda *a: output_one)
self.stubs.Set(json, "loads", lambda *a: output_two)

the result is see is only the output_two as output_one is getting overwritten. How should i mock a method twice and expect different output each time.

Was it helpful?

Solution

Use side_effect.

Example from docs:

>>> mock = Mock()
>>> mock.side_effect = [3, 2, 1]
>>> mock(), mock(), mock()
(3, 2, 1)

OTHER TIPS

You need to move the code into two test functions.

def test_output_one():
    self.stubs = stubout.StubOutForTesting()
    self.stubs.Set(json, "loads", lambda *a: output_one)
    ... code for the first test here ...

def test_output_two():
    self.stubs = stubout.StubOutForTesting()
    self.stubs.Set(json, "loads", lambda *a: output_two)
    ... code for the second test here ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top