79141302

Date: 2024-10-30 13:31:11
Score: 1
Natty:
Report link

We use junit 4.12, and also have the same problem that any test which throws an exception is marked as passed, which seems illogical and dangerous.

There are several solutions suggested on various forums, which I have compiled here. Most dont work (for us). The one which requires wrapping every test in try/catch/fail is the only working solution, but this would require a lot of work to add if you have thousands of tests.

This is the suggested solution with Junit 5:

import org.junit.jupiter.api.Assertions;
public class NoExceptionTest {
    @Test
    public void testNoException() {
        assertDoesNotThrow(() -> {
            // code that is expected to not throw an exception
        });
    }
}

This is a suggested method with Junit 4:

@Test(expected = NoException.class)
public void testMethod() {
    // Code that should not throw an exception goes here
}

The above did not work for us.

Another post suggests this:

@Rule
public ExpectedException exception = ExpectedException.none();

But this did not work either.

This solution suggested by @vinay works, but requires wrapping every tests, which is a significant task if you have thousands of tests.

@Test
public void foo(){
   try{
      //execute code that you expect not to throw Exceptions.
   }
   catch(Exception e){
      fail("Should not have thrown any exception");
   }
}
Reasons:
  • Blacklisted phrase (1): did not work
  • Long answer (-1):
  • Has code block (-0.5):
  • Me too answer (2.5): also have the same problem
  • User mentioned (1): @vinay
  • High reputation (-2):
Posted by: John Little