本文介绍了python unittest assertRaises在assertRaises失败时抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码,当 assertRaises 失败时,assertRaises 会抛出异常.我认为如果 assertRaises 失败,那么测试就会失败,最后我会得到一个报告,说测试失败.我没想到会抛出异常.下面是我的代码.我是不是做错了什么?我使用的是 Python 2.6.2.

I've got code where assertRaises throws an exception when assertRaises fails. I thought that if assertRaises fails then the test would fail and I'd get a report at the end that says the test failed. I wasn't expecting the exception to be thrown. Below is my code. I'm I doing something wrong? I'm using Python 2.6.2.

import unittest

class myClass:

    def getName(self):

        raise myExcOne, "my exception one"
        #raise myExcTwo, "my exception two"
        #return "a"

class myExcOne(Exception):
    "exception one"

class myExcTwo(Exception):
    "exception two"


class test_myClass(unittest.TestCase):

    def setUp(self):

        self.myClass = myClass()

    def testgetNameEmpty(self):
        #self.assertRaises(myExcOne,self.myClass.getName)
        #self.assertRaises(myExcTwo,self.myClass.getName)

        try:
            self.assertRaises(myExcTwo,self.myClass.getName)
        except Exception as e:
            pass

if __name__ == "__main__":

    #unittest.main()

    suite = unittest.TestLoader().loadTestsFromTestCase(test_myClass)
    unittest.TextTestRunner(verbosity=2).run(suite)

推荐答案

从旁白开始,class 语句中 classname 后面的 () 是完全正确的现代 Python —— 根本不是错误.

Starting with an aside, the () after the classname in a class statement is perfectly correct in modern Python -- not an error at all.

关于问题的实质,assertRaises(MyException, foo) 记录传播通过调用 foo() 其类型不是 MyException 的子类——它只捕获 MyException 及其子类.当您的代码引发一种类型的异常并且您的测试期望一种不同的不相关类型时,引发的异常将传播,根据 unittest 模块的文档,这里,我引用:

On the meat of the issue, assertRaises(MyException, foo) is documented to propagate exceptions raised by calling foo() whose type is NOT a subclass of MyException -- it only catches MyException and subclasses thereof. As your code raises an exception of one type and your test expects one of a different unrelated type, the raised exception will then propagate, as per the docs of the unittest module, here, and I quote:

如果引发异常,则测试通过,如果引发另一个异常,则测试为错误,如果未引发异常,则测试失败.

是一个错误"意味着传播另一个异常".

And "is an error" means "propagates the other exception".

当您捕获在 try/except 块中传播的异常时,您消除了错误,并且 unittest 没有什么可诊断的了.如果你的目的是把这个错误变成失败(一个有争议的策略......),你的 except 块应该调用 self.fail.

As you catch the exception propagating in your try/except block, you nullify the error, and there's nothing left for unittest to diagnose. If your purpose is to turn this error into a failure (a debatable strategy...), your except block should call self.fail.

这篇关于python unittest assertRaises在assertRaises失败时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:39
查看更多