使用以下测试(JUnit4),不会调用断言。这是预期的行为吗?我希望引发ResponseStatusException,测试将对此进行验证,但随后我希望对响应进行断言。还是将推理作为异常抛出来检查响应的内容是否无效?
@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());
}
是的,这很正常,不过请注意,无论如何您将无法验证响应,因为会引发异常,因此您不会获得响应!但是,您可以验证异常状态。
为此,您可能需要阅读Junit 4官方文档的“异常测试”页面(从那里获取的代码),在这里您基本上使用assertThrows
而不是方法,该方法@Test(expected=)
可以进行更多的验证。
另一种选择是使用ExpectedException Rule
。同样,请参见链接以获取示例。
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());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句