user_mda
user_mda

Reputation: 19388

Testing Exception in junit tests fails even after the exception is thrown

Hello I am unit testing a method using the junit @Rule annotation ,

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

@Test
public void testException() {
  //do something that throws RuntimeException
  exception.expect(RuntimeException.class);
}

The test fails with the Runtime exception when it should actually pass expecting the exception. Is there anything else I need to do ?

Upvotes: 0

Views: 142

Answers (1)

Stefan Birkner
Stefan Birkner

Reputation: 24510

exception.expect(RunTimeException.class) must be called before the code that throws the exception is executed.

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

@Test
public void testException() {
  exception.expect(RunTimeException.class);
  //do something that throws RunTimeException
}

Upvotes: 1

Related Questions