如何用pytest测试类构造方法中是否抛出ValueError异常
使用pytest测试Foo类构造方法的异常抛出
你可以在TestFoo类中编写以test_开头的测试方法,pytest会自动识别并执行。下面是两种常用的实现方式:
方式一:上下文管理器捕获异常(基础用法)
这种方式直接直观,能精准验证异常类型和消息:
import pytest from your_module import Foo # 替换成Foo类实际所在的模块名 class TestFoo: def test_init_raises_value_error_with_negative_bar(self): # 用pytest.raises包裹会抛出异常的代码 with pytest.raises(ValueError) as exc_info: Foo(bar=-1) # 可选:验证异常的提示文本是否符合预期 assert str(exc_info.value) == "bar must be positive."
方式二:参数化测试(多场景验证)
如果要测试多个负数输入的情况,用参数化能让代码更简洁高效:
import pytest from your_module import Foo class TestFoo: # 参数化传入多个测试用例 @pytest.mark.parametrize("negative_bar", [-1, -10, -100]) def test_init_raises_error_for_various_negative_values(self, negative_bar): with pytest.raises(ValueError) as exc_info: Foo(bar=negative_bar) assert str(exc_info.value) == "bar must be positive."
核心要点:
- 测试方法必须以
test_开头,这是pytest的识别规则 pytest.raises作为上下文管理器,只有捕获到指定类型的异常,测试才会通过exc_info对象存储了异常的详细信息,可用来验证异常消息的准确性- 务必确保导入了
Foo类,替换代码中的your_module为实际的模块名称
内容的提问来源于stack exchange,提问作者CHRIBUR_
相关产品推荐
相关产品推荐

