0

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).

Boon
  • 1,073
  • 1
  • 16
  • 42
  • You can just mock it as usual, e.g. something like `@mock.patch("foo.Bar")` (provided you import it like `from bar import Bar`). Maybe I don't understand the question? – MrBean Bremen May 11 '21 at 18:07

1 Answers1

0

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
Peter K
  • 1,959
  • 1
  • 16
  • 22