Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Junit test case fail if there is any exception in the code?

Tags:

java

junit

junit4

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.

like image 799
Rishi Arora Avatar asked Apr 25 '16 04:04

Rishi Arora


2 Answers

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");
   }
}
like image 127
Vinay Avatar answered Oct 13 '22 00:10

Vinay


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
  }
}
like image 40
Sergii Bishyr Avatar answered Oct 13 '22 01:10

Sergii Bishyr