java - How can I test several exceptions within one test using an ExpectedException Rule? -
got question regarding usage of junit's expectedexception rule:
as suggested here: junit expectedexception rule starting junit 4.7 1 can test exceptions (which better @test(expected=exception.class)):
@rule public expectedexception exception = expectedexception.none(); @test public void testfailuresofclass() { foo foo = new foo(); exception.expect(exception.class); foo.dostuff(); } now needed test several exceptions in 1 test method , got green bar after running following test , thought every test passed.
@test public void testfailuresofclass() { foo foo = new foo(); exception.expect(indexoutofboundsexception.class); foo.dostuff(); //this not tested anymore , if first passes looks fine exception.expect(nullpointerexception.class); foo.dostuff(null); exception.expect(myownexception.class); foo.dostuff(null,""); exception.expect(domainexception.class); foo.dootherstuff(); } however after while realized testmethod quit after first check passes. ambiguous least. in junit 3 possible... here question:
how can test several exceptions within 1 test using expectedexception rule?
short answer: can't.
if first call - foo.dostuff() - throws exception, never reach foo.dostuff(null). you'll have split test several (and trivial case i'd propose going simple notation, without expectedexception):
private foo foo; @before public void setup() { foo = new foo(); } @test(expected = indexoutofboundsexception.class) public void noargsshouldfail() { foo.dostuff(); } @test(expected = nullpointerexception.class) public void nullargshouldfail() { foo.dostuff(null); } @test(expected = myownexception.class) public void nullandemptystringshouldfail() { foo.dostuff(null,""); } @test(expected = domainexception.class) public void dootherstuffshouldfail() { foo.dootherstuff(); } if want 1 , 1 test, can fail if no error thrown, , catch things expect:
@test public void testfailuresofclass() { foo foo = new foo(); try { foo.dostuff(); fail("dostuff() should not have succeeded"); } catch (indexoutofboundsexception expected) { // want. } try { foo.dostuff(null); fail("dostuff(null) should not have succeeded"); } catch (nullpointerexception expected) { // want. } // etc other failure modes } this gets quite messy pretty fast, though, , if first expectation fails, won't see if else fails well, can annoying when troubleshooting.
Comments
Post a Comment