Home > Software engineering >  Mocking/patching an object attribute to test a method (also need access to other class methods)
Mocking/patching an object attribute to test a method (also need access to other class methods)

Time:03-15

I have a method of a class I'd like to test with pytest, such as the method _method_of_interest below.

class MyClass():
    def __init__(self, stuff):
     ...
    ..
    ..
    def _method_of_interest(self, list1, list2):
        """
        some logic that depends on list1, list2, and self.relevant_info
        Also calls self._helper_method(list)
        """
        output = list1   list2   self._helper_method(list2)   self.relevant_info

  
        return output 

    def _helper_method(self, lista):
        """
        Helper method depends on lista and self.relevant_info
        """
        
        return lista   self.relevant_info

I'd like to be able to test _method_of_interest with different values of list1, list2, and self.relevant_info. So I mostly need to be able to specify a value for self.relevant_info. What is the cleanest way to do this with Python?

CodePudding user response:

The easiest approach would be to use the builtin unittest framework.

Define multiple test cases. In each, you create a new MyClass object with the stuff defined for that test. Then you compare the output of my_class._method_of_interest to some predefined expected output (with the assertEqual method of unittest.TestCase). Of course, you can do multiple test, for multiple different lists 1&2.

EDIT: If you can't set relevant_info through the constructor itself then you can always manually adjust it. Class attributes are not protected in python, no-one can stop you from doing:

my_class = MyClass(unrelevant_info)
my_class.relevant_info = relevant_info

But if you need to do it then there is something fishy going on in the code.

  • Related