Java – how to use the expectedexception rule to test multiple exceptions in a test?

There are questions about the usage of JUnit's expectedexception rule:

As suggested here, the JUnit expectedexception rule starts with JUnit 4.7 and can test such exceptions (which is much better than @ 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 I need to test several exceptions in a test method and get a green bar after running the following tests, so I think each test has passed

@Test
public void testFailuresOfClass() {
 Foo foo = new Foo();

 exception.expect(indexoutofboundsexception.class);
 foo.doStuff();

 //this is not tested anymore and if the first passes everything looks fine
 exception.expect(NullPointerException.class);
 foo.doStuff(null);

 exception.expect(MyOwnException.class);
 foo.doStuff(null,"");

 exception.expect(DomainException.class);
 foo.doOtherStuff();
}

But after a while, I realized that after the first check passed, the test method would exit This is ambiguous, to say the least In JUnit 3, this is easy to implement... So this is my question:

How to use the expectedexception rule to test multiple exceptions in a test?

Solution

Short answer: you can't

If – foo. Is called for the first time Dostuff() – throw an exception and you'll never get to foo doStuff(null). You must divide your test into several (for this simple case, I suggest returning to simple symbols 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 you really want one and only one test, if you don't throw an error, you will fail and catch what you expect:

@Test
public void testFailuresOfClass() {
 Foo foo = new Foo();

 try {
    foo.doStuff();
    fail("doStuff() should not have succeeded");
 } catch (indexoutofboundsexception expected) {
    // This is what we want.
 }
 try {
    foo.doStuff(null);
    fail("doStuff(null) should not have succeeded");
 } catch (NullPointerException expected) {
    // This is what we want.
 }
 // etc for other failure modes
}

However, this will soon become very chaotic. If the first expectation fails, you won't see anything else fail, which will be very annoying when troubleshooting

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>