问题
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)
回答1:
The code as posted is wrong. For a start, class myClass():
shoudl be class myClass:
. Also if name == "main":
should be:
if __name__ == "__main__":
unittest.main()
Apart from these problems, this fails because getName()
is raising exception myExcOne
and your test expects exception myExcTwo
.
Here is some code that works. Please edit the code in your question so that it is easy for us to cut and paste it into a Python session:
import unittest
class myExcOne(Exception): "exception one"
class myExcTwo(Exception): "exception two"
class myClass:
def getName(self):
raise myExcTwo
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)
if __name__ == "__main__":
unittest.main()
回答2:
Starting with an aside, the ()
after the classname in a class
statement is perfectly correct in modern Python -- not an error at all.
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:
The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised.
And "is an error" means "propagates the other exception".
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
.
来源:https://stackoverflow.com/questions/1230498/python-unittest-assertraises-throws-exception-when-assertraises-fails