Python OOP测试未通过求助:page_count属性赋值校验失效
Book类单元测试失败:赋值非整数page_count无预期输出
问题详情
写了个Python的Book类,本地运行看似正常,但过不了单元测试。测试要求给page_count赋非整数值时输出指定字符串,结果测试断言显示未捕获到预期输出。
我的代码
class Book: def __init__(self, title, page_count): self.title = title if isinstance(page_count, int): self.page_count = page_count else: print("page_count must be an integer")
测试失败信息
def test_requires_int_page_count(self): '''prints "page_count must be an integer" if page_count is not an integer.''' book = Book("And Then There Were None", 272) captured_out = io.StringIO() sys.stdout = captured_out book.page_count = "not an integer" sys.stdout = sys.__stdout__ > assert captured_out.getvalue() == "page_count must be an integer\n" E AssertionError: assert '' == 'page_count m... an integer\n' E - page_count must be an integer
问题根因
你的代码只在创建对象初始化阶段做了page_count的类型检查和打印,但测试是在对象创建完成后直接给book.page_count赋值,这时候走的是Python默认的属性赋值逻辑,根本没触发你写的检查代码,所以没有输出。
修复方案
用Python的@property装饰器给page_count添加setter方法,这样无论是初始化还是后续赋值,都会经过类型检查:
class Book: def __init__(self, title, page_count): self.title = title self._page_count = None # 调用setter完成初始化,确保检查逻辑生效 self.page_count = page_count @property def page_count(self): return self._page_count @page_count.setter def page_count(self, value): if isinstance(value, int): self._page_count = value else: print("page_count must be an integer")
关键说明
- 用
_page_count作为私有存储变量,避免和@property装饰的page_count名称冲突 - 初始化时通过
self.page_count = page_count调用setter,保证初始化阶段的类型检查也能生效 - 后续给
book.page_count赋值时,会自动触发setter里的逻辑,满足测试的输出要求
内容的提问来源于stack exchange,提问作者Levin Mwanganyi
相关产品推荐
相关产品推荐

