06、pytest将多个测试放在一个类中

官方用例

python 复制代码
# content of test_class.py
# 实例1
class TestClass:
    def test_one(self):
        x = "this"
        assert "h" in x
        
    def test_two(self):
        x = "hello"
        assert hasattr(x,"check")
python 复制代码
# content of test_class_demo.py
# 每个测试都有唯一的类实例
class TestClassDemoInstance:
    
    value = 0
    
    def test_one(self):
        self.value = 1
        assert self.value == 1
        
    def test_two(self):
        assert self.value == 1

解读与实操

​ 一旦开发了多个测试,你可能希望将它们分组到一个类中。pytest可以很容易地创建一个包含多个测试的类。

​ 确保为类添加Test前缀,否则将跳过该类。

将测试分组到类是有益的,原因如下:

  • 更好的组织测试
  • 仅在该特定类中共享fixture
  • 在类级别应用mark,并将其隐式应用于所有测试

在类中对测试进行分组时需要注意的是,每个测试都有一个唯一的类实例。让每个测试共享相同的类实例将非常不利于测试隔离,并会造成糟糕的测试实践。

场景应用

​ 程序开发过程由面向函数发展到面向对象,测试用例也可以通过面向对象进行设计,更好的感受pytest带来的便利。

相关推荐
我的xiaodoujiao1 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest
sky0Lan1 天前
一个类似 pytest 的 html 报告
android·html·pytest
一半烟火以谋生2 天前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
一半烟火以谋生4 天前
pytest conftest.py 使用教程
pytest
我的xiaodoujiao4 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 19--测试框架Pytest基础 3--前后置操作应用
python·学习·测试工具·pytest
鱼鱼说测试4 天前
pytest+yaml+allure接口自动化测试框架
pytest
ThreeAu.7 天前
pytest 实战:用例管理、插件技巧、断言详解
python·单元测试·pytest·测试开发工程师
我的xiaodoujiao7 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 18--测试框架Pytest基础 2--插件和参数化
python·学习·测试工具·pytest
小小测试开发8 天前
pytest 库用法示例:Python 测试框架的高效实践
开发语言·python·pytest
know__ledge8 天前
Pytest+requests进行接口自动化测试8.0(Allure进阶 + 文件上传接口 + 单接口多用例)
pytest