我想测试如果找不到考试,则会引发Bad Request Exception。
private static String BASE_PATH = "http://localhost:8080/exams/";
@Test
public void testQuizStatusException() {
final String url = BASE_PATH + null + "/status/";
try {
ResponseEntity<String> result = restTemplate.getForEntity(url, String.class);
assertThat(result.getStatusCodeValue(), equalTo(HttpStatus.BAD_REQUEST.value()));
} catch (HttpClientErrorException e) {
e.printStackTrace();
}
}
然后我收到以下消息:
org.springframework.web.client.HttpClientErrorException$NotFound: 404 Not Found: [<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
这条路是正确的,但我不明白为什么我会得到不同的Http code
。
我检查了-Spring error - springframework.web.client.HttpClientErrorException: 404 Not Found,但问题似乎有所不同。
答案 0 :(得分:2)
我会将您的测试重构为在expected
批注上使用@Test
,并删除测试中的异常处理以让expected
处理它。
@Test(expected = HttpClientErrorException.NotFound.class)
public void testQuizStatusException() {
final String url = BASE_PATH + null + "/status/";
ResponseEntity<String> result = restTemplate.getForEntity(url,....);
}
答案 1 :(得分:1)
应该返回的http状态代码完全取决于您的实现,此处没有提到,因此我假设您使用的是默认代码。通常,如果没有在url中指定的资源,框架将遵循标准惯例及其标准惯例来返回404。在您的情况下,这是真的,因为在服务器上找不到null
考试,因此您的状态为404 - Not Found
。如果
400 - Bad request
由于明显,服务器无法或将不处理请求 客户端错误(例如,请求语法格式错误,大小太大,无效 请求消息框架或欺骗性请求路由)
有关更多详细信息,请参见https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400