Source From Here
Question
We have been using Mock for python for a while. Now, we have a situation in which we want to mock a function:
Normally, the way to mock this would be (assuming foo being part of an object):
Even, if i call foo() a couple of times i can use:
Now, I am facing a situation in which I want to return a fixed value when the input parameter has a particular value. So if let's say "my_param" is equal to "something" then I want to return "my_cool_mock"
This seems to be available on mockito for python:
I have been searching on how to achieve the same with Mock with no success? Any idea?
How-To
If side_effect is a function then whatever that function returns is what calls to the mock return. The side_effect function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input. Consider below function my_side_effect:
Then we can use it to customized the mock function output:
We have been using Mock for python for a while. Now, we have a situation in which we want to mock a function:
- def foo(self, my_param):
- #do something here, assign something to my_result
- return my_result
- self.foo = MagicMock(return_value="mocked!")
- self.foo = MagicMock(side_effect=["mocked once", "mocked twice!"])
This seems to be available on mockito for python:
- when(dummy).foo("something").thenReturn("my_cool_mock")
How-To
If side_effect is a function then whatever that function returns is what calls to the mock return. The side_effect function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input. Consider below function my_side_effect:
- def my_side_effect(value):
- return value + 1
沒有留言:
張貼留言