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

相关推荐
奶茶精Gaaa3 天前
pytest
pytest
霍格沃兹测试开发学社测试人社区5 天前
软件测试学习笔记丨Pytest 学习指南
软件测试·笔记·测试开发·学习·pytest
神即道 道法自然 如来7 天前
测试面试题:pytest断言时,数据是符点类型,如何断言?
pytest
high_tea7 天前
pytest - 多线程提速
python·pytest
傻啦嘿哟9 天前
自动化测试框架集成:将Selenium集成到pytest与unittest中
selenium·测试工具·pytest
一名在八月份找工作的测试员10 天前
自动化学习1:pytest自动化框架的基本用法:注意事项/断言assert/测试结果分析
学习·自动化·pytest
什么时候才能变强11 天前
Pytest-如何将allure报告发布至公司内网
linux·服务器·pytest
一名在八月份找工作的测试员11 天前
自动化学习2:pytest的高级用法(mark标记/fixture/hook)
学习·自动化·pytest
测试199812 天前
Python+requests+pytest+allure自动化测试框架
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest