Reputation: 3186
If I have 2 classes as such:
public class A {
public A(boolean bool){
if(bool){
// currently broken
// would throw RuntimeException
}
B.doSomething();
}
}
and
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?
Upvotes: 1
Views: 3183
Reputation: 693
If you don't have a specific RuntimeException
to catch (subclass of RuntimeException
) then the only way I see is to put a try catch
in your testA
method and in the catch
, verify if the exception does not contain a nested exception then rethrow the exception or call Assert.fail()
Upvotes: 0
Reputation: 3300
You should typically stay away from 'raw' exception classes anyway, so the correct way to solve this would be to create a subclass of RuntimeException
that reflects what has actually gone wrong.
That way you could refer to the correct subclass of RuntimeException
in your test case and you should be OK.
Upvotes: 0
Reputation: 1500903
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.
Upvotes: 1