如何使用 pytest fixture 实例化被测对象?

How to use a pytest fixture to instantiate a object under test?

似乎应该使用固定装置来实例化 pytest 的被测对象,尤其是当它被多个 test_ 函数使用时。但是,在尝试调整 pytest 文档中给出的示例后,我无法使以下内容正常工作。

import pytest
...
@pytest.fixture
def newMyClass():
    obj = MyClass(1,2)

...
def test_aMethod(newMyClass):
    objectUnderTest = newMyClass.obj
    ...

没有关于夹具或构造函数的投诉,但后来我收到 pytest 错误

   def test_aMethod(newMyClass):
>      objectUnderTest = newMyClass.obj()
E      AttributeError: 'NoneType' object has no attribute 'obj'

如果灯具可以用于此,应该如何编码?

要清理@hoefling 的答案,您需要直接实例化您的 class 和 return 该实例。如果您正在寻找清理后的版本,请查看此代码。

import pytest

class MyClass():
  def __init__(self, obj, foo):
      self.obj = obj
      self.foo = foo

@pytest.fixture
def newMyClass():
    myClassInstance = MyClass(1,2)
    return myClassInstance

def test_aMethod(newMyClass):
    objectUnderTest = newMyClass.obj
    assert objectUnderTest