简体   繁体   English

如何正确地对FileNotFoundError进行单元测试

[英]How to properly unit test FileNotFoundError

With the unittest module, how can I test FileNotFoundError is raised when opening a file as follows: 使用unittest模块,打开文件时,如何测试FileNotFoundError是否引发如下:

func(filename):
    try:
        file = open(filename)
    except FileNotFoundError:
        exit()

Unittest module 单元测试模块

class TestFunc(unittest.TestCase):

    def test_func(self):
        self.assertRaises(FileNotFoundError, func, "no_exist.txt")

Resulting error 结果错误

AssertionError: FileNotFoundError not raised by func AssertionError:函数未引发FileNotFoundError

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. 您正在吞没异常处理程序中的异常,因此调用代码(单元测试)无法知道错误已引发,所看到的只是代码已运行并退出。

Consider re-raising as in : 考虑重新筹款,如:

func(filename):
    try:
        file = open(filename)
    except FileNotFoundError:
        # Whatever else you want to do 
        raise

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. 考虑模拟open方法,以便您拥有更多控制权。

Use context manager for Exception 使用上下文管理器处理异常

Changed in version 2.7: Added the ability to use assertRaises() as a context manager. 在2.7版中进行了更改:添加了使用assertRaises()作为上下文管理器的功能。

If only the exception argument is given, returns a context manager so that the code under test can be written inline rather than as a function: 如果仅给出exception参数,则返回一个上下文管理器,以便可以将内嵌代码而不是作为函数编写被测代码:

with self.assertRaises(SomeException):
    do_something()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM