I wrote a Junit test to unit test my code. I want my Junit test case to fail when I get any exception in my code. I tried using an assert statement, but even when I get an exception in my code, my Junit test case is passing. Please can anyone tell me how I can achieve this? Thanks.
I strongly recommend that you must test your functionality only. If an exception is thrown, the test will automatically fail. If no exception is thrown, your tests will all turn up green.
But if you still want to write the test code that should fail the in case of exceptions, do something like :-
@Test
public void foo(){
try{
//execute code that you expect not to throw Exceptions.
}
catch(Exception e){
fail("Should not have thrown any exception");
}
}
Actually your test should fail when an exception in code is thrown. Of course, if you catch this exception and do not throw it (or any other exception) further, test won't know about it. In this case you need to check the result of method execution. Example test:
@Test
public void test(){
testClass.test();
}
Method that will fail the test:
public void test(){
throw new RuntimeException();
}
Method that will not fail the test
public void test(){
try{
throw new RuntimeException();
} catch(Exception e){
//log
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With