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

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");
   }
}

In JUnit 4, you can explicitly assert that a @Test should fail with a given exception using the expected property of the @Test annotation:

  @Test(expected = NullPointerException.class)
  public void expectNPE {
     String s = null;
     s.toString();
  }

See JUnit4 documentation on it.


Both the following tests will fail without further coding:

@Test
public void fail1() {
    throw new NullPointerException("Will fail");
}

@Test
public void fail2() throw IOException {
    throw new IOException("Will fail");
}

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
  }
}

Tags:

Java

Junit

Junit4