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

相关推荐
2601_962078232 小时前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言
杨女士YRJ2 小时前
python+pytest+01
python·pytest
2601_962078231 天前
Python接口自动化框架:pytest
python·pytest·接口自动化·测试框架·restfulapi
2601_962078191 天前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
2601_962284503 天前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_962300813 天前
基于pytest的接口自动化测试:使用requests模块的实战项目与接口关联方法详解
接口自动化测试·测试用例·pytest·接口关联·requests模块
2601_962300813 天前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
11路没有终点4 天前
Pytest 安装、版本与第一个测试用例
测试用例·pytest
11路没有终点5 天前
pytest 参数化与 Mark 标记
pytest
2601_962296285 天前
五种Python自动化测试框架汇总,附学习方法
自动化测试·pytest·unittest·robotframework·python框架