Skip to main content
 首页 » 编程设计

python之IOError 异常处理的单元测试

2025年02月15日9Renyi-Fan

给定这段代码:

 try: 
        #do something 
 except IOError as message: 
        logging.error(message) 
        raise message 

我想测试异常处理部分以便全面覆盖。 在我试过的单元测试中:

        with patch(new=Mock(side_effect=IOError(errno.EIO))): 
            self.assertRaises(IOError) 

但它不起作用。 这种做法是否正确?

请您参考如下方法:

实际上您需要启动 Mock 以便 side_effect 启动,例如以下内容:

class Test(unittest.TestCase): 
 
    def test(self): 
        mock = m.Mock() 
        mock.side_effect = Exception("Big badaboum") 
        self.assertRaises(Exception, mock) 

self.assertRaises 可以将可调用对象作为第二个参数,使其等效于:

class Test(unittest.TestCase): 
    def test(self): 
        mock = m.Mock() 
        mock.side_effect = Exception("Big badaboum") 
        with self.assertRaises(Exception): 
            mock() 

如果你想在补丁测试中使用它,你可以执行以下操作:

import unittest.mock as m 
import unittest 
 
def raise_error(): 
    try: 
        print("Hello") #placeholder for the try clause 
    except Exception as e: 
        print(e) #placeholder for the exceptclause 
 
class Test(unittest.TestCase): 
    @m.patch("__main__.raise_error", side_effect=Exception("Big badaboum")) #replace  __main__ by the name of the module with your function 
    def test(self, mock): 
        with self.assertRaises(Exception): 
            mock() 
 
unittest.main() 

编辑:要测试 except block 内错误的引发,您需要在您编写的 try block 内模拟函数调用,例如:

import unittest.mock as m 
import unittest 
 
def do_sthing(): 
    print("Hello") 
 
def raise_error(): 
    try: 
        do_sthing() #this call can be mocked to raise an IOError 
    except IOError as e: 
        print(e.strerror) 
        raise ValueError("Another one") 
 
class Test(unittest.TestCase): 
    def test(self): 
        with m.patch("__main__.do_sthing", side_effect=IOError("IOError")): 
            self.assertRaises(ValueError, raise_error) 
 
 
unittest.main() 

您也可以使用装饰器语法(只需重写上面的测试以节省一些 CPU 周期):

class Test(unittest.TestCase): 
    @m.patch("__main__.do_sthing",side_effect=IOError("IOError")) 
    def test(self, mock): 
        self.assertRaises(ValueError, raise_error)