用pytes测试类方法

2024-05-13 18:48:09 发布

您现在位置:Python中文网/ 问答频道 /正文

在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()


Tags: 模块方法文档pytestself示例pytest
3条回答

测试类方法所需做的就是实例化该类,并在该实例上调用该方法:

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

一种方法是在测试方法中创建对象并从中与之交互:

def test_action(self, x):
    o = SuperCool()
    assert o.action(2) == 4

显然,您可以使用下面的方法使用类似于经典的setupteardown样式的unittest:http://doc.pytest.org/en/latest/xunit_setup.html

我不能百分之百确定它们是如何使用的,因为pytest的文档是非常糟糕的。

编辑:很明显,如果你做了

class TestSuperCool():
    def setup(self):
        self.sc = SuperCool()

    ... 

    # test using self.sc down here

我只使用任何fixture来创建测试环境(比如数据库连接)或数据参数化。

如果您的数据相对简单,可以在测试用例中定义它:

def test_action_without_fixtures():
    sc = SuperCool()
    sc.element = 'snow'
    sc.melt()
    assert sc.element == 'water'

参数化示例:

@pytest.mark.parametrize("element, expected", [('snow', 'water'), ('tin', 'solder')])
def test_action_with_parametrization(element, expected):
    sc = SuperCool()
    sc.element = element
    sc.melt()
    assert sc.element == expected

相关问题 更多 >