python - 如何对引发异常而不引发异常进行单元测试以使程序终止
问题描述
根据要求,我需要对已引发异常(SearchMiss)进行单元测试。我肯定可以用 assertRaises 做到这一点。但是第二个要求是应该引发异常,但在引发异常时程序不应终止/崩溃。
如果我不在异常块中添加重新引发部分,程序将不会终止,但是单元测试会说没有引发异常。
关于如何做到这一点的建议?我应该使用其他测试方法吗?
我提出这样的异常:
def find_word(self, word):
""" Checks if given word exists """
try:
if self.trie.find_word(word): # Checks if word exists first
return True # Returns bool, true if found else false
raise SearchMiss
except SearchMiss:
SearchMiss.print_error()
raise ## If I delete this raise the program won't crash but the test case will fail
return false
测试用例:
def test_raise_search_miss(self):
""" Tests raise search miss """
with self.assertRaises(SearchMiss):
self.spellchecker.delete_word("")
注意:拼写检查器 delete_word 方法正在调用引发异常的 find_word 方法。
解决方案
如果您可以包含您想要满足的确切要求,那将会很有帮助。
从您写的内容来看,我认为您不应该在find_word
. 让我们find_word
提高 SearchMiss。然后,您的单元测试可以检查它是否这样做。
另外,当您调用find_word
from时delete_word
,将其包装在 try/except 中,这样它就不会终止您的程序。
推荐阅读
- abap - 为什么我可以动态调用继承类的公共方法,但不能调用受保护的方法?
- html - 在画布外面放置一个形状,不增加它们的大小
- html - 打印视图中的边距扩大
- kubernetes - aws-iam-authenticator & EKS
- python - 连接到 mqtt 代理 docker 容器的测试 docker 容器中的 Python mqtt 客户端
- python - Python isdigit 无法识别数字
- react-native - 用户登录后删除登录屏幕的导航堆栈
- imap - imap_search 通过正文中的超链接搜索
- java - 如果我要求用户输入一个文件,而该文件不存在,如何在程序不停止的情况下继续询问文件名?
- azure - 如何在完成 X 个其他 Azure 功能时触发 Azure 功能?