我想使用 pytest 来测试类的构造函数中是否引发 ValueError [重复]

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

有一堂课:

class Foo:
    def __init__(self, bar: int) -> None:
        self.bar = bar
        if self.bar < 0:
            raise ValueError("bar must be positive.")
    
   ...

我想测试 pytest 是否引发 ValueError,但我对它不熟悉,所以我不知道如何编写代码。

import pytest

class TestFoo:

我写不出下一行。

python constructor pytest
1个回答
-1
投票
def test_foo_raises_when_instantiating():
    with pytest.raises(ValueError):
        Foo(-1)
© www.soinside.com 2019 - 2024. All rights reserved.