Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit-test a method without instantiating the class?

I have a class SocketHandler with a method calculate_ticket:

class SocketHandler(A, B, C ..):
    ..

    calculate_ticket(self, key):
        ..
        return ticket

    ..

Now I want to test the method without having to instantiate the class since it is coupled with so many things. Is this possible?

like image 657
Pithikos Avatar asked Nov 01 '25 10:11

Pithikos


1 Answers

There are several ways using the mock library. One simple way is to mock the instance itself, then call the method using the "long" form.

class ClassToTest(object):
    def __init__(self):
        pass

    def method_to_test(self, y):
        self.x = y
        return 5

fake_instance = mock.Mock()
ClassToTest.__init__(fake_instance)
x = ClassToTest.method_to_test(fake_instance, 3)
assert x == 5
assert fake_instance.x == 3
like image 144
chepner Avatar answered Nov 02 '25 23:11

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!