【问题标题】:pytest not allowing classes with non-static methodspytest 不允许使用非静态方法的类
【发布时间】:2017-02-16 11:57:56
【问题描述】:

我正在关注 pytest 的本教程:

http://doc.pytest.org/en/latest/getting-started.html#grouping-multiple-tests-in-a-class

但注意到如果我创建:

class ComplexTestClass:
    """
    Complex and more nuanced tests for specific sentences
    """
    def test_multiple_sentences():

如果我没有在函数顶部添加@staticmethod,我会在函数上出现一个错误,它无法使用() is 获取,并且它在我的 PyCharm 中以红色突出显示。

教程(显示不需要静态方法)是错的,还是我错了,staticmethod 会使我的测试无效?

【问题讨论】:

    标签: python unit-testing oop static-methods pytest


    【解决方案1】:

    如果您不将其声明为 @staticmethod,则需要在方法中使用 self 参数:

    def test_multiple_sentences(self):
    

    【讨论】:

    • 根据pytest 文档,为什么它有没有self 和没有_init_ 的示例?我的目标是在我运行测试时在pytest 及其所有方法中调用该类。当我运行pytest -q test_text.py 时,staticmethod 会阻止这种情况吗?
    • 您链接到的确切示例确实self作为参数。该页面上没有self 参数的示例是在class 之外定义的函数,而不是方法。按照您链接到的示例(即不要将您的测试方法声明为 @staticmethods 并包含 self 参数)并且您的所有测试用例都应该运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 2016-10-04
    • 1970-01-01
    相关资源
    最近更新 更多