0

I have the following situation:

mixin_foo.py
   class Foo:
      def doFoo(self):
        bar=self.defined_elsewhere()
        #....do work

Unit test:

@patch('path_to_mixin_foo.mixin_foo.Foo.defined_elsewhere')
def test_do_foo(self, definedElsewhere)
    definedElsewhere.return_value = bar1
    self.FooTester.doFoo()

the defined_elsewhere() method is defined in a class that derives from that mixin. However, for development purposes, we are working on mixing_foo.Foo first before integrating it with the class. However, when I try to unit test the doFoo method, the following error is shown by pytest: Attributeerror <....> does not have the attribute 'defined_elsewhere'. Is my patch correct and if there another way to unit test this method? Basically I want to mock out the call/return value of the self.defined_elsewhere so the doFoo method can be tested.

laconicdev
  • 6,360
  • 11
  • 63
  • 89

1 Answers1

1

The problem with your approach is that you try to patch a non-existent property. You cannot patch defined_elsewhere because it is not defined in Foo, but you can derive from Foo, add the method, and patch the Foo class instead:

class TestFoo(path_to_mixin_foo.Foo):
    def do_something(self):
        return bar1


@patch('path_to_mixin_foo.mixin_foo.Foo', TestFoo)
def test_do_foo(self)
    self.FooTester.doFoo()
MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46