I am trying to use unittest with unittest.mock to do some tests in my application.
I have two classes MainClass and Caller. I would like to test main class with a double Caller. This is in short what I have:
class MainClass:
def __init__(self, caller):
self.caller = caller
def some_function(self):
self.caller.function1()
blab = self.caller.function2()
class Caller:
# some functions non of which should be accessed in tests
class CallerMock:
def __init__(self):
self.items = []
def function1(self):
pass
def function2(self):
return items
In the test I do:
class TestMainFunction(unittest.TestCase):
def setUp(self):
self.mock = MagicMock(wraps=CallerMock())
self.main_class = MainClass(self.mock)
def test(self):
# self.main_class.caller.items = items
# self.mock.items = items
# self.mock.function2.return_value = items
self.main_class.some_functions()
# non of the above change the return value of function2
However the problem is that non of the commented lines actually change the return value of my function2. How can I achieve this?
I would be also happy with a solution where I don't need the double and all the functions of the Caller would return None and I would have to specify the return values of functions in particular tests.
You could just mock the Caller
, and patch the call()
method. That way, you won't need a double:
def setUp(self):
self.mocked_caller = mock.Mock(spec=Caller)
self.mocked_caller.call.return_value = items
self.main_class = MainClass(self.mocked_caller)
def test(self):
self.main_class.some_function()
self.assertTrue(self.mocked_caller.called)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.