简体   繁体   English

如何使用pytest中的fixture测试类__init__方法引发异常

[英]How to test that class __init__ method raises exception using fixture in pytest (Python)

I am trying to get some more skills with pytest (unit testing). 我正在尝试通过pytest(单元测试)获得更多技能。

I try to test if an exception is raised when a class is instantiated without a must have parameter. 我尝试测试在实例化没有必须具有参数的类时是否引发异常。

I tried to create a fixture for that but this leads to a problem that when the fixture is called it tries to create the class inside it with missing parameter and raises my exception before pytest actually asserts that the exception was raised. 我试图为此创建一个固定装置,但这会导致一个问题,当调用固定装置时,它将尝试在其中缺少参数的类中创建类,并在pytest实际断言引发异常之前引发异常。

I managed to overcome this by not using fixture and just instantiating the class inside the test function but I wonder if there is a more elegant way of using a fixture for that. 我设法通过不使用Fixture并仅在测试函数中实例化类来克服了这一点,但是我想知道是否有一种更优雅的方法来为此使用Fixture。

Example class: 示例类:

class MyClass(object):

    def __init__(self, must_have_parameter=None):

    if not must_have_parameter:

        raise ValueError("must_have_parameter must be set.")

When trying to use this fixture in a test I naturally get an error. 尝试在测试中使用此治具时,我自然会出现错误。

@pytest.fixture()
def bad_class_instantiation():

    _bad_instance = MyClass()

    return _bad_instance

Then there is a test: 然后有一个测试:

def test_bad_instantiation(bad_class_instantiation):

    with pytest.raises(ValueError, message="must_have_parameter must be set."):

        bad_class_instantiation()

This test fails as the class gets instantiated before the test case runs (That is my interpretation)? 由于在测试用例运行之前实例化了该类,因此该测试失败(这是我的解释)? It still shows that a ValueError occured and the custom message gets displayed.. 它仍然显示发生ValueError并显示自定义消息。

If I change the test case to: 如果我将测试用例更改为:

def test_bad_instantiation():

    with pytest.raises(ValueError, message="must_have_parameter must be set."):

        bad_instance = MyClass()

Then the test passes. 然后测试通过。

Is there a way of using a fixture for this or I should just call the class inside the test function and call it a day ? 有没有办法为此使用夹具,或者我应该只在测试函数中调用该类并每天调用它?

Thanks for your time. 谢谢你的时间。

Tomasz 托马斯

I don't see any benefit to the fixture in this situation. 在这种情况下,我认为该装置没有任何好处。 I would just create the object in the test method. 我只是在测试方法中创建对象。

Having an optional parameter with a default value and then raising an exception when the parameter is missing seems very strange. 拥有一个带有默认值的可选参数,然后在缺少该参数时引发异常似乎很奇怪。 Unless you really need a custom error message, consider removing the default value. 除非您确实需要自定义错误消息,否则请考虑删除默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM