Testing class methods with pytest

laserbrain picture laserbrain · Sep 8, 2016 · Viewed 32.8k times · Source

In the documentation of pytest various examples for test cases are listed. Most of them show the test of functions. But I’m missing an example of how to test classes and class methods. Let’s say we have the following class in the module cool.py we like to test:

class SuperCool(object):

    def action(self, x):
        return x * x

How does the according test class in tests/test_cool.py have to look?

class TestSuperCool():

    def test_action(self, x):
        pass

How can test_action() be used to test action()?

Answer

elethan picture elethan · Sep 8, 2016

All you need to do to test a class method is instantiate that class, and call the method on that instance:

def test_action(self):
    sc = SuperCool()
    assert sc.action(1) == 1