我正试图通过pytest(单元测试)获得更多技能。
我尝试测试在没有必需参数的情况下实例化类时是否引发异常。
我试图为此创建一个fixture,但这会导致一个问题,即当调用fixture时,它会尝试在其中创建缺少参数的类,并在pytest实际断言引发了异常之前引发我的异常。
我通过不使用fixture而只是在测试函数内实例化类来克服这一问题,但我想知道是否有更优雅的方法来使用fixture。
示例类:
class MyClass(object):
def __init__(self, must_have_parameter=None):
if not must_have_parameter:
raise ValueError("must_have_parameter must be set.")
当我试图在测试中使用这个夹具时,我自然会出错。
@pytest.fixture()
def bad_class_instantiation():
_bad_instance = MyClass()
return _bad_instance
然后有一个测试:
def test_bad_instantiation(bad_class_instantiation):
with pytest.raises(ValueError, message="must_have_parameter must be set."):
bad_class_instantiation()
这个测试失败了,因为类在测试用例运行之前被实例化(这是我的解释)?
它仍然显示发生了ValueError,并且显示了自定义消息。。
如果我将测试用例更改为:
def test_bad_instantiation():
with pytest.raises(ValueError, message="must_have_parameter must be set."):
bad_instance = MyClass()
然后测试通过。
有没有一种方法可以使用fixture来实现这一点,或者我应该只调用测试函数内的类,并在一天内调用它?
谢谢你抽出时间。
托马什