使用pytest测试类方法

2022-03-01 00:00:00 python pytest

问题描述

在pytest文档中列出了测试用例的各种示例。它们中的大多数都是功能测试。但是我缺少一个如何测试类和类方法的示例。假设我们要测试的模块cool.py中有以下类:

class SuperCool(object):

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

tests/test_cool.py中相应的测试类必须是什么样子?

class TestSuperCool():

    def test_action(self, x):
        pass

如何使用test_action()测试action()


解决方案

测试类方法只需实例化该类,然后调用该实例上的方法:

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

相关文章