首页 > 解决方案 > 使用 pytest 测试类方法 - 错误 - 找不到夹具“自我”

问题描述

我想测试一个类方法,py.test我已经按照这篇文章使用 pytest 测试类方法

我的方法有calgo.py一个文件test_calgo.pylearning_ut

当我运行 pytest 时,我收到一条错误消息说fixture 'self' not found.

我哪里错了?

谢谢!

# calgo.py 
class MyClass():
    def func(self, x):
        return x+1

# test_calgo.py
import calgo 
def test_func(self):
    mc = MyClass()
    assert mc.func(3) == 4

# Command line 
(pyenv) C:\Users\Jimmy\Desktop\learning_ut>pytest 

# Error message
(pyenv) C:\Users\Jimmy\Desktop\learning_ut>pytest
================================================= test session starts =================================================
platform win32 -- Python 3.6.13, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: C:\Users\Jimmy\Desktop\learning_ut
collected 1 item
test_calgo.py E   [100%]
======================================================= ERRORS ========================================================
_____________________________________________ ERROR at setup of test_func _____________________________________________
file C:\Users\Jimmy\Desktop\learning_ut\test_calgo.py, line 11
  def test_func(self):
E       fixture 'self' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, 
doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, 
record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.
C:\Users\Jimmy\Desktop\learning_ut\test_calgo.py:11
=============================================== short test summary info ===============================================
ERROR test_calgo.py::test_func

标签: pythonpytest

解决方案


我不知道pytest,在unittest您创建一个测试类时,该类将具有属于此类的方法并具有self作为参数。但是,您的错误似乎是由 in 中的函数引起的,该函数calgo.py不属于某个类,因此没有自引用。尝试以下操作:


import calgo 
def test_func():
    mc = MyClass()
    assert mc.func(3) == 4


推荐阅读