0

I have a class and within that class there are used methods from another classes. Let's say it looks like that (just an example):

from jobs.fruit import Fruit
from jobs.veggie import Veggie

class Healthy:
    def start(self, arg):
        self.start_connection()
        if len(arg) == 1 or self.check(arg):
            fruit = Fruit()
            fruit.start()
            return 1
        else:
            veggie = Veggie()
            veggie.update()
            return 0

I'm writting unit tests for my Healthy class, and the start looks like this:

def test_start():
    healthy = Healthy()
    healthy.start_connection = MagicMock(return_value=1)
    healthy.check = MagicMock(return_value=True)
    fruit = Fruit()
    fruit.start = MagicMock(return_value = 0)
    result = healthy.start()

Unfortunately when running the test it doesn't take fruit.start mocked value, but it tries to run original method. How should I mock that class or method and pass that info to the method that I'm testing? I never had to mock something from outside the class that I'm testing and got a bit stuck with it. I'd prefer to stick to unittest mock to not mess with several methods in the code so it's clear for my coworkers. Thanks in advance!

nola
  • 1
  • `Healthy` is fundamentally coupled to `Fruit` and `Veggie`, because it creates instances of them inside its own method. You therefore probably _shouldn't_ be mocking anything. There's certainly no connection between the specific instances `fruit` and `healthy`. And you definitely shouldn't mock the methods on the thing you're supposed to be testing. – jonrsharpe Jun 06 '22 at 15:48
  • I have Fruit and Veggie fully covered with unit tests, but now I was asked to cover Healthy as well. I'd say the output of them it's not important in this test that I'm writting and would prefer to mock that output. Also a side note - my method is much more complex than what we see here, but for obvious reasons couldn't paste it here. 'Fruit' and 'Veggie' are very small parts of that method and they are not really important for the test, but for various reasons we would prefer them to not run, but be mocked. Do you think it's possible? – nola Jun 06 '22 at 16:00

0 Answers0