I want to write a test to establish that an Exception is not raised in a given circumstance.
It\'s straightforward to test if an Exception is raise
One straight forward way to ensure the object is initialized without any error is to test the object's type instance.
Here is an example :
p = SomeClass(param1=_param1_value)
self.assertTrue(isinstance(p, SomeClass))
you can try like that. try: self.assertRaises(None,function,arg1, arg2) except: pass if you don't put code inside try block it will through exception' AssertionError: None not raised " and test case will be failed. Test case will be pass if put inside try block which is expected behaviour.
I've found it useful to monkey-patch unittest
as follows:
def assertMayRaise(self, exception, expr):
if exception is None:
try:
expr()
except:
info = sys.exc_info()
self.fail('%s raised' % repr(info[0]))
else:
self.assertRaises(exception, expr)
unittest.TestCase.assertMayRaise = assertMayRaise
This clarifies intent when testing for the absence of an exception:
self.assertMayRaise(None, does_not_raise)
This also simplifies testing in a loop, which I often find myself doing:
# ValueError is raised only for op(x,x), op(y,y) and op(z,z).
for i,(a,b) in enumerate(itertools.product([x,y,z], [x,y,z])):
self.assertMayRaise(None if i%4 else ValueError, lambda: op(a, b))
Just call the function. If it raises an exception, the unit test framework will flag this as an error. You might like to add a comment, e.g.:
sValidPath=AlwaysSuppliesAValidPath()
# Check PathIsNotAValidOne not thrown
MyObject(sValidPath)