Python类参数校验:unittest的assertRaises测试失败问题排查
问题原因分析及修复方案
核心问题
__init__方法吞噬了异常
在Footer类的__init__方法中,你使用try-except块捕获了validInput()抛出的异常,但仅打印错误信息却没有重新抛出异常。这导致传入非整数参数创建Footer实例时,异常不会传播到测试代码中,assertRaises无法检测到预期的TypeError。assertRaises使用方式错误
在测试代码的attempt 1中,你直接调用footer1.validInput()并将返回值传给assertRaises,但assertRaises需要接收**可调用对象(函数本身)**而非函数执行结果。这会导致validInput()提前抛出异常,使测试直接失败。
修复步骤
第一步:修改Footer类,让异常能够传播
修改__init__方法,在打印错误信息后重新抛出异常,确保测试代码能捕获到它:
class Footer: def __init__(self, current_page: int, total_pages: int, boundaries: int, around: int): self.current_page = current_page self.total_pages = total_pages self.boundaries = boundaries self.around = around try: if self.validInput(): footer = self.createFooter() self.addEllipsis(footer) except Exception as e: print(f"\nError while initializing Footer Class ({e.__class__}).\n Please fix the following: ", e) raise # 重新抛出异常,让测试代码可以捕获 # 其余方法保持不变
如果不需要打印错误信息,也可以直接移除整个try-except块,让异常自然传播。
第二步:修正测试代码
拆分测试用例为独立方法,每个测试仅验证一个逻辑,并正确使用assertRaises:
import unittest from footer import Footer class TestFooter(unittest.TestCase): def test_valid_input(self): # 验证合法输入可正常初始化,且validInput返回True footer = Footer(4,5,1,0) self.assertTrue(footer.validInput()) def test_invalid_types_raise_type_error(self): # 验证传入非整数参数创建实例时抛出TypeError with self.assertRaises(TypeError): Footer("four",5,1,0) def test_valid_input_method_raises_type_error(self): # 直接测试validInput方法对非法类型的处理 footer = Footer.__new__(Footer) # 绕过__init__手动设置属性 footer.current_page = "four" footer.total_pages = 5 footer.boundaries = 1 footer.around = 0 with self.assertRaises(TypeError): footer.validInput() if __name__ == '__main__': unittest.main()
测试验证
修复后运行测试,三个用例都会通过:
test_valid_input:验证合法输入正常工作test_invalid_types_raise_type_error:验证初始化时传入非法类型会抛出TypeErrortest_valid_input_method_raises_type_error:验证validInput方法本身可正确检测非法类型
内容的提问来源于stack exchange,提问作者Simao
相关产品推荐
相关产品推荐

