如何正确地对 FileNotFoundError 进行单元测试 [英] How to properly unit test FileNotFoundError
问题描述
使用 unittest
模块,如何测试 FileNotFoundError
在打开文件时引发如下:
With the unittest
module, how can I test FileNotFoundError
is raised when opening a file as follows:
func(filename):
try:
file = open(filename)
except FileNotFoundError:
exit()
单元测试模块
class TestFunc(unittest.TestCase):
def test_func(self):
self.assertRaises(FileNotFoundError, func, "no_exist.txt")
导致错误
AssertionError: FileNotFoundError 不是由 func 引发的
AssertionError: FileNotFoundError not raised by func
推荐答案
您在异常处理程序中吞下了异常,因此您的调用代码(单元测试)无法知道错误已引发,所有它看到的是您的代码已运行并退出.
You are swallowing the exception inside your exception handler, so there is no way your calling code (the unit test) can know that the error has been raised, all it sees is that your code has run, and exited.
考虑再加注:
func(filename):
try:
file = open(filename)
except FileNotFoundError:
# Whatever else you want to do
raise
更好的是,您的单元测试不应该真正依赖于不存在的文件 - 单元测试应该是自包含的定义.考虑模拟 open 方法,以便您有更多控制权.
Better still, your unit test shouldn't really be depending on that file not existing - unit tests should be self contained by definition. Consider mocking the open method so you have more control.
这篇关于如何正确地对 FileNotFoundError 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!