wedson soares
wedson soares

Reputation: 15

How to test methods of an class that don't have parameters or returns in python using pytest

Let's say that I have a class, this class have some attributes and some methods. This methods don't have any parameters or any return, they only work by changing the attributes of the class using the 'self.' property. How can I test these types of methods?

Let's create the imaginary class Foo to serve as example:

class Foo:
     example_value = -1

     def function_1(self,a,b):
        self.attr1 = a
        self.attr2 = b

        self.function_2()
        self.function_3()
        self.function_4(self.example_value)


    def function_2(self):
        self.attr1 = self.attr1 + 50
        self.attr2 = self.attr2 + 40

    def function_3(self):
        self.attr1 = self.attr1 * 2
        self.attr2 = self.attr3 * 3
        self.example_value = self.attr1 + self.attr3

    def function_4(self,value):
        
        if value == -1:
            raise Exception('snippet')   

In order to test this class, what should I mock? Since two of the methods don't have any input parameters or returns, how can I track the value change of the class attributes? Should I mock only a method or the entire class? And how can I do it in a simple way with pytest? What could be changed in this code? The addition of a simple get_value() would simplify the test development for this class?

Upvotes: 0

Views: 849

Answers (1)

azro
azro

Reputation: 54148

You may just verify the attributes, after the method being called, something like this:

from unittest import TestCase


class TestFoo(TestCase):

    def test_f1(self):
        x = Foo()
        x.function_1(10, 20)
        self.assertEqual(x.attr1, 120)
        self.assertEqual(x.attr2, 30)
        self.assertEqual(x.attr3, 10)
        self.assertEqual(x.example_value, 130)

    def test_f4(self):
        try:
            Foo().function_4(1)
        except Exception:
            self.fail("function_4() raised Exception unexpectedly!")

    def test_f4_error(self):
        with self.assertRaises(Exception):
            Foo().function_4(-1)

Upvotes: 2

Related Questions