简体   繁体   中英

Testing response after expected exception is thrown

Using below test (JUnit4) the Asserts are not invoked. Is this the expected behaviour? I expect ResponseStatusException to be thrown, the test verifies this but then I wish to assert on the response. Or is the reasoning as an exception is thrown checking the content of the response is not valid?

@Test(expected = ResponseStatusException.class)
public void testResponse(){

    final Long ticketId = null

    when(service.getTicket(null))
            .thenThrow(new NullPointerException("ticketId cannot be null"));

    //Execute
    ResponseEntity<List<TicketResponse>> response = service.getTicket(null);

    assertEquals(HttpStatus.OK, response.getStatusCode());


}

Yes, this is normal, though note you won't be able to verify the response anyway, as an exception is thrown so you don't get a response. You could verify the exception state however.

For that, you might want to read up on the "Exception Testing" page of the official Junit 4 documentation (code taken from there), where you basically use the assertThrows method and not @Test(expected=) , which allows you to do more verifications.

Another alternative would be using the ExpectedException Rule . Again, see the link for an example.

https://github.com/junit-team/junit4/wiki/Exception-testing

@Test
public void testExceptionAndState() {
  List<Object> list = new ArrayList<>();

  IndexOutOfBoundsException thrown = assertThrows(
      IndexOutOfBoundsException.class,
      () -> list.add(1, new Object()));

  // assertions on the thrown exception
  assertEquals("Index: 1, Size: 0", thrown.getMessage());
  // assertions on the state of a domain object after the exception has been thrown
  assertTrue(list.isEmpty());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM