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带来的便利。

相关推荐
词元Max3 天前
2.12 pytest 实战:如何测试 AI 应用
人工智能·pytest
biter down4 天前
11:pytest 框架 assert 验证测试
服务器·windows·pytest
biter down4 天前
14:pytest-order 插件 顺序控制案例
开发语言·python·pytest
我的xiaodoujiao5 天前
API 接口自动化测试详细图文教程学习系列21--结合Pytest框架使用2--断言和插件
python·学习·测试工具·pytest
我的xiaodoujiao5 天前
API 接口自动化测试详细图文教程学习系列22--结合Pytest框架使用3-分组、跳过执行和参数化处理
python·学习·测试工具·pytest
测试员周周9 天前
【Appium 系列】第13节-混合测试执行器 — API + UI 的协同执行
开发语言·人工智能·python·功能测试·ui·appium·pytest
旦莫11 天前
一个完美的AI测试Agent应该是什么样的
人工智能·python·测试开发·pytest·ai测试
我的xiaodoujiao11 天前
API 接口自动化测试详细图文教程学习系列20--结合Pytest框架使用
python·学习·测试工具·pytest