1

I have a method that throws exception. And i have a test like this.

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

@Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
    doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());

    expectedEx.expect(InvalidException.class);
    expectedEx.expectMessage("Invalid Token");

    // my method call

    // verify DB save doesn't happens

    assertTrue(false);
}

The test assert for exception, and since the exception is thrown the test passes. It doesn't care about the last line assertTrue(false)

How can i make sure that my other assertions are also satisfied.

Prasanna
  • 10,956
  • 2
  • 28
  • 40

1 Answers1

1

This is the pattern I follow for this case. It uses ExpectedException as designed. I like the throw e rather than failing after method method call in the try because it will not result in a false-positive if someone decides to delete the fail (which people have a tendency to do when they see fail() or if a test is failing because it hits a fail()).

@Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
  doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());

   expectedEx.expect(InvalidException.class);
   expectedEx.expectMessage("Invalid Token");

   try{
     // my method call
   }catch(InvalidException e){
     // verify DB save doesn't happens

    assertTrue(false);

    throw e;
  }
 }
John B
  • 32,493
  • 6
  • 77
  • 98