单元测试
单元测试 单元测试的目的并不是查找bug,而是帮助我们更好的设计我们的代码,如何合理的来拆分我们的代码。 单元测试vs集成测试 集成测试检查各个组件间协作运行是否正常,单元测试检查应用程序中的一个某一个小的功能模块。 相关工具 以python为例 unittest nose or nose2 pytest 其中,nose和nose2基于unittest, 如果使用python2可以使用前两中,pytest要求python3.7+。pytest有较多插件, 显示内容更为丰富一些。 用官方例子比较一下: 1 2 3 4 5 6 # content of test_sample.py def inc(x): return x + 1 def test_answer(): assert inc(3) == 5 直接运行pytest 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [garlic@centos8 pytest]$ pytest ========================================= test session starts ========================================= platform linux -- Python 3.6.8, pytest-7.0.1, pluggy-1.0.0 rootdir: /home/garlic/pytest/pytest collected 1 item test_sample.py F [100%] ============================================== FAILURES =============================================== _____________________________________________ test_answer _____________________________________________ def test_answer(): > assert inc(3) == 5 E assert 4 == 5 E + where 4 = inc(3) test_sample.py:7: AssertionError ======================================= short test summary info ======================================= FAILED test_sample.py::test_answer - assert 4 == 5 ========================================== 1 failed in 0.03s ========================================== [garlic@centos8 pytest]$ cat test_sample.py # content of test_sample.py def inc(x): return x + 1 def test_answer(): assert inc(3) == 5 如果用unittest要写成下面的样子: ...