user12051965
user12051965

Reputation: 147

Spring Test - HttpClientErrorException Not Found

I want to test that Bad Request Exception will be thrown if it will not find an exam.

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();
    }
}

And I get the following message:

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>

The path is right but I do not understand why I get different Http code.

I checked - Spring error - springframework.web.client.HttpClientErrorException: 404 Not Found but it seems the problem is different.

Upvotes: 1

Views: 2981

Answers (2)

Jayesh
Jayesh

Reputation: 999

I would refactor your test to use expected on the @Test annotation and remove the exception handling in your test to let expected handle it.

@Test(expected = HttpClientErrorException.NotFound.class)
public void testQuizStatusException() {
    final String url = BASE_PATH + null + "/status/";
    ResponseEntity<String> result = restTemplate.getForEntity(url,....);             
}

Upvotes: 2

ravinikam
ravinikam

Reputation: 3696

What http status code should be returned is totally based on your implementation, which you did not mentioned here, so I am assuming you are using default one. Usually frameworks follow standard practices and its standard practice to return 404 if resource specified in url is not found. Which is in your case is true, since null exam not found on server, you get 404 - Not Found status.400 - Bad request will be returned if

The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, size too large, invalid request message framing, or deceptive request routing)

For more details see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400

Upvotes: 1

Related Questions