如何测试 class __init__ 方法在 pytest (Python) 中使用夹具引发异常
How to test that class __init__ method raises exception using fixture in pytest (Python)
我正在尝试使用 pytest(单元测试)获得更多技能。
我尝试测试在 class 没有必须有参数的情况下实例化时是否引发异常。
我试图为此创建一个固定装置,但这会导致一个问题,即当调用固定装置时,它会尝试在其中创建缺少参数的 class 并在 pytest 实际断言之前引发我的异常出现异常。
我设法通过不使用夹具而只是在测试函数中实例化 class 来克服这个问题,但我想知道是否有更优雅的方法来使用夹具。
示例class:
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()
此测试失败,因为 class 在测试用例运行之前被实例化(这是我的解释)?
它仍然显示发生了 ValueError 并显示了自定义消息。
如果我把测试用例改成:
def test_bad_instantiation():
with pytest.raises(ValueError, message="must_have_parameter must be set."):
bad_instance = MyClass()
然后测试通过。
有没有办法为此使用夹具,或者我应该在测试函数中调用 class 并结束它?
感谢您的宝贵时间。
托马斯
在这种情况下,我看不到夹具有任何好处。我只会在测试方法中创建对象。
有一个带有默认值的可选参数,然后在缺少该参数时引发异常似乎很奇怪。除非您确实需要自定义错误消息,否则请考虑删除默认值。
我正在尝试使用 pytest(单元测试)获得更多技能。
我尝试测试在 class 没有必须有参数的情况下实例化时是否引发异常。
我试图为此创建一个固定装置,但这会导致一个问题,即当调用固定装置时,它会尝试在其中创建缺少参数的 class 并在 pytest 实际断言之前引发我的异常出现异常。
我设法通过不使用夹具而只是在测试函数中实例化 class 来克服这个问题,但我想知道是否有更优雅的方法来使用夹具。
示例class:
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()
此测试失败,因为 class 在测试用例运行之前被实例化(这是我的解释)? 它仍然显示发生了 ValueError 并显示了自定义消息。
如果我把测试用例改成:
def test_bad_instantiation():
with pytest.raises(ValueError, message="must_have_parameter must be set."):
bad_instance = MyClass()
然后测试通过。
有没有办法为此使用夹具,或者我应该在测试函数中调用 class 并结束它?
感谢您的宝贵时间。
托马斯
在这种情况下,我看不到夹具有任何好处。我只会在测试方法中创建对象。
有一个带有默认值的可选参数,然后在缺少该参数时引发异常似乎很奇怪。除非您确实需要自定义错误消息,否则请考虑删除默认值。