[英]How to test that class __init__ method raises exception using fixture in pytest (Python)
我正在尝试通过pytest(单元测试)获得更多技能。
我尝试测试在实例化没有必须具有参数的类时是否引发异常。
我试图为此创建一个固定装置,但这会导致一个问题,当调用固定装置时,它将尝试在其中缺少参数的类中创建类,并在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()
然后测试通过。
有没有办法为此使用夹具,或者我应该只在测试函数中调用该类并每天调用它?
谢谢你的时间。
托马斯
在这种情况下,我认为该装置没有任何好处。 我只是在测试方法中创建对象。
拥有一个带有默认值的可选参数,然后在缺少该参数时引发异常似乎很奇怪。 除非您确实需要自定义错误消息,否则请考虑删除默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.