Reputation: 677
I am using Mock for Python Unit Testing. I am testing a function foo
which contains a function bar
that doesn't return anything, but fills a variable x
(type:io.StringIO) as a side effect. I have mocked bar
using MagicMock, but I don't know how to assign to x
from a test script.
I have the following situation:
def foo():
x = io.StringIO()
bar(x) # x is filled with some string by bar method
here some operation on x
To write a Unit Test case for foo
, I have mocked bar
with MagicMock (return value=None) but how to assign to x
which is needed by foo
.
Upvotes: 3
Views: 2014
Reputation: 122516
You need to mock io.StringIO
and you can then replace it with something else:
@mock.patch('mymodule.io.StringIO')
def test_foo(self, mock_stringio):
mock_stringio.return_value = mock.Mock()
Note the use of return_value
which means you're mocking the instance that's returned from the StringIO()
call.
Upvotes: 4