[pytest]测试类中引入__init__(self)方法问题,有坑莫入

问题展示

在使用pytest做一些测试的时候,如果惯性思维采用了__init__(self)初始化的方法,这就给自己挖了一个坑,在使用pytest最好不要碰__init__(self)方法,
demo code:

class TestApi:
    def __init__(self):
        print('init')

    def test_login(self):
        print('login test')

运行之后,Termial出现黄色提示,并且没有找到case,这里我们看下报错类型:

================================== test session starts ==================================
platform win32 -- Python 3.7.0, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: D:\python\office_txt\DemoTest
plugins: allure-pytest-2.9.43, arraydiff-0.2, doctestplus-0.1.3, openfiles-0.3.0, remotedata-0.3.3
collected 0 items  
================================== warnings summary ===================================
test_1.py:10
  D:\python\office_txt\DemoTest\test_1.py:10: PytestCollectionWarning: cannot collect test class 'TestApi' because
it has a __init__ constructor (from: test_1.py)
    class TestApi:

-- Docs: https://docs.pytest.org/en/stable/warnings.html
================================= 1 warning in 0.10s ====================================

日志解读

log中有标志:collected 0 items并没有找到我们的case
提示上说:
it has a __init__ constructor
就是这个初始化构造器导致的,所以避免踩坑,不要在code中使用初始化;
[pytest]测试类中引入__init__(self)方法问题,有坑莫入_第1张图片

解决方案

作为测试用例的class类不可以有__init__(self)方法

结果验证

注释掉__init__(self)方法,再次运行,查看结果
demo code:

class TestApi:
    # def __init__(self):
    #     print('init')

    def test_login(self):
        print('login test')

结果:
collected 1 item:可以读到case了

=============================================== 1 warning in 0.10s ===============================================

(base) D:\python\office_txt\DemoTest>pytest
================================= test session starts ===================================
platform win32 -- Python 3.7.0, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: D:\python\office_txt\DemoTest
plugins: allure-pytest-2.9.43, arraydiff-0.2, doctestplus-0.1.3, openfiles-0.3.0, remotedata-0.3.3
collected 1 item                                                                                                  

test_1.py .                                                                                                 [100%]

=================================== 1 passed in 0.12s ======================

over~~~

你可能感兴趣的:(测试工具,pytest,python)