Stack Overflow Asked on December 27, 2021
Mocking a method with mock is simple enough, for instance, like this:
o.get_idlist = mock.Mock(return_value=[1])
However, that will make get_idlist()
return [1]
every time. Is there a way to make it return [1]
only once, and subsequent calls return []
(for instance) without using side_effect=somefun
? I guess what I want is a kind of side effect, but there you go.
(I just think it’s so clumsy to create a big honking named function just for that… or is there a way to use a lambda here?)
Assuming you don't have anything against side_effect
itself but just don't want to create a whole function, you could roughly do something like the following
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = [1] + [[]]*100
>>> m()
1
>>> m()
[]
>>> m()
[]
>>> m()
[]
>>> m()
[]
I admit it's a bit dirty but if you just want to make a quick test it should be sufficient. Of course you could replace [] with [0] or whatever you like.
Answered by F. Pareto on December 27, 2021
I think the only way to do what you want with python-mock
library is using a side_effect
.
I can give you an alternative:
Take a look to mockito library. With it is easy to make what you want:
from mockito import when
when(o).get_idlist().thenReturn([1]).thenReturn([])
Answered by jvallver on December 27, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP