How to tell JUnit to ignore nested exceptions?

If I have 2 classes as such:

public class A {

    public A(boolean bool){
            // currently broken
            // would throw RuntimeException


public class B {

    public static void doSomething() throws RuntimeException{
        throw new RuntimeException();

and my unit test for class A would be along the lines of:

public class ATest {
    @Test (expected=RuntimeException)
    public void testA(){
        new A(true);

As it is, the test would succeed due to class B method also throwing a RuntimeException and the fact that A is broken would not be immediately visible.

Is it possible to tell JUnit to somehow ignore the exceptions coming from B without the use of mocking frameworks?

Jon Skeet

No - the result of calling the method is a RuntimeException, and that's what you're testing. How is JUnit meant to tell the difference between a RuntimeException from the exact method you're calling, and one from a dependent call? One of the rules of testing is that you're not meant to care about the details of how the result is obtained, just that it is obtained. (For example, you might move the code within the block in the A constructor into a separate method, and that shouldn't break the test.)

At the moment, you should be able to easily have a failing test just by checking that calling new A(false) doesn't throw an exception. Currently that test will fail, because you're still calling B.doSomething(), which will still throw.

Note that most mocking frameworks won't help with this either, as you're using a static method - you should at least consider making B an injected dependency (possibly with an interface) so allow for more control.


See more on this question at Stackoverflow