0

I have a ClassA that has multiple methods, one of the methods returns an object of ClassB, where class B has it’s own methods

myfile1.py:

from b import ClassB

class ClassA(object):

    def method_1(self):
        f = ClassB()
        return f.method_a()

    def method_2(self):
        ...
        return ...

    def method_n(self):
        ...
        return ...

myfile2.py:

class ClassB(object):

    def __init__(self):
        self.var1 = "something"

    def method_a(self):
        return self.var1

    def method_b(self):
        return ...
      
    ...

    def method_z(self):
        return ...

In test function I am trying to mock return values for all ClassA methods, including method_1 that initiates ClassB.

myfile3.py:

from myfile1 import ClassA

class ClassC(object):
    
    def __init__(self):

    self.a = ClassA()

Could someone please explain what is the proper way to patch and mock Class A and B?

If we want to mock each method from method_1 to method_n return value from ClassA and make mocked values re usable by other test functions, what is the proper way of doing it as the approach below will make test function too long and not re usable:

@patch("myfile3.ClassA")
    def test1(mock_class_a):
        mock_class_a().method_1.return_value = "abc"
Ale
  • 645
  • 4
  • 16
  • 38

1 Answers1

0

create a bunch of mock classes and use those instead

#./something/__init__.py
class X:
   def get_class_thing(self):
       return "not abc"

#./tests/tests.py
from unittest.mock import Mock,patch
class MyMock:
      get_class_thing = Mock(return_value="abc")
      method_2 = Mock(return_value="abc")

@patch('something.X',return_value=MyMock)
def test_it(patched):
   from something import X
   assert X().get_class_thing() == "abc"
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179