Selenium实战(八)——pytest单元测试(1)

一、简介

  相比于unittest,更加简单、灵活,且提供了更加丰富的扩展,弥补了unittest在做Web自动化测试时的一些不足。

  官方网站:https://docs.pytest.org/en/latest/

  安装:pip install pytest

一个简单的测试用例,test_sample.py

1 def inc(x):
2     return x + 1
3 
4 
5 def test_answer():
6     assert inc(3) == 4

 切换到命令行窗口执行:pytest

 

 优点汇总:

  • 不必像unittest一样必须创建测试类;
  • 使用assert断言比unittest提供的断言方法更简单

自己的规则:测试文件和测试函数必须以“test”开头。这也是在执行“pytest"命令时并没有指定测试文件也可以执行test_sample.py文件的原因,因为该文件名以"test"开头。

二、和unittest的对比

三、pytest中的main 

 1 import pytest
 2 
 3 
 4 def inc(x):
 5     return x + 1
 6 
 7 
 8 def test_answer():
 9     assert inc(3) == 4
10 
11 
12 if __name__ == '__main__':
13     pytest.main()

   main()方法默认执行当前文件中所有以"test"开头的函数。现在可以直接在IDE中运行测试了。

posted @ 2020-03-02 10:52  pegawayatstudying  阅读(191)  评论(0编辑  收藏  举报