Imagine a class like so:
class Foo():
def method_1(self):
bar = Bar()
bazz = Bazz(bar)
return bazz.method_2()
For unit testing, how can we mock the Bar
object when we never call any methods on it, we're just passing it as a parameter to the Bazz
constructor? (Yes, this is not ideal, but this pattern can be found in a top-level class wiring together different objects via dependency injection).
You do call the Bar
object, when you execute: bar = Bar()
, so you can easily mock it:
mock_bar = mocker.MagicMock(name='Bar')
mocker.patch('foo.Bar', new=mock_bar)
# mock_foo.return_value = the new mocked object
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.