首页 > 解决方案 > 如何对引发异常而不引发异常进行单元测试以使程序终止

问题描述

根据要求,我需要对已引发异常(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 方法。

标签: python

解决方案


如果您可以包含您想要满足的确切要求,那将会很有帮助。

从您写的内容来看,我认为您不应该在find_word. 让我们find_word提高 SearchMiss。然后,您的单元测试可以检查它是否这样做。

另外,当您调用find_wordfrom时delete_word,将其包装在 try/except 中,这样它就不会终止您的程序。


推荐阅读