401未经授权的spring boot测试

时间:2021-06-06 20:57:48

标签: java spring spring-boot junit resttemplate

我写了一个测试,我希望得到 401,但我得到了一个例外。 当我在调试模式下运行测试时,我看到在 HttpUrlConnection.class 中处理了 401 状态(请在下面找到它)并且我收到一个异常响应 我想知道如何解决这个问题并通过测试?

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserAuthenticationTest {

    @Test
    public void unAuthenticatedRequestTest() {
        String url = "/user/favorite/add/{marketId}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, String> urlParams = new HashMap<>();
        urlParams.put("marketId", "1");

        URI uri = UriComponentsBuilder.fromUriString(url)
                .buildAndExpand(urlParams)
                .toUri();
        uri = UriComponentsBuilder
                .fromUri(uri)
                .queryParam("favoriteName", "something")
                .build()
                .toUri();

        ResponseEntity<Favorite> favoriteResponseEntity = testRestTemplate.exchange(
                uri, HttpMethod.PUT, new HttpEntity<>(headers), Favorite.class);

        Assertions.assertEquals(HttpStatus.UNAUTHORIZED, favoriteResponseEntity.getStatusCode());
    }
}

HttpUrlConnection.class

      if (respCode == 401) {
                            if (this.streaming()) {
                                this.disconnectInternal();
                                throw new HttpRetryException("cannot retry due to server authentication, in streaming mode", 401);
                            }

这是我运行测试时得到的错误:

org.springframework.web.client.ResourceAccessException: I/O error on PUT request for "http://localhost:36725/user/favorite/add/1": cannot retry due to server authentication, in streaming mode; nested exception is java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode

1 个答案:

答案 0 :(得分:0)

我发现了问题,401状态是从servlet过滤器设置的,所以它从不返回Favorite.class的ResponseEntity,但它返回Void.class的ResponseEntity。 所以当期望Favorite.class的ResponseEntity时,它重试访问资源并且不能,所以它抛出ResourceAccessException。