如何使用pytest固定装置实例化被测对象?

问题描述 投票:0回答:1

似乎应该使用固定装置来为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'

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

object pytest instantiation fixtures
1个回答
0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.