unittest: assertRaises() with an instance instead of a type

Ethan Furman ethan at stoneleaf.us
Thu Mar 29 17:35:16 CEST 2012

Steven D'Aprano wrote:
> On Wed, 28 Mar 2012 14:28:08 +0200, Ulrich Eckhardt wrote:
>> Hi!
>> I'm currently writing some tests for the error handling of some code. In
>> this scenario, I must make sure that both the correct exception is
>> raised and that the contained error code is correct:
>>    try:
>>        foo()
>>        self.fail('exception not raised')
>>    catch MyException as e:
>>        self.assertEqual(e.errorcode, SOME_FOO_ERROR)
>>    catch Exception:
>>        self.fail('unexpected exception raised')
> Secondly, that is not the right way to do this unit test. You are testing 
> two distinct things, so you should write it as two separate tests:

I have to disagree -- I do not see the advantage of writing a second 
test that *will* fail if the first test fails as opposed to bundling 
both tests together, and having one failure.


More information about the Python-list mailing list