programing

TestRestTemplate 사용 시 예외 발생

topblog 2023. 7. 22. 09:08
반응형

TestRestTemplate 사용 시 예외 발생

나는 정상적으로 작동하는 사용자 정의 인증 필터가 있는 일반적인 SpringBoot 응용 프로그램을 가지고 있습니다.

그러나 통합 테스트에서 TestRestTemplate를 사용할 때 문제가 있습니다.

잘못된 자격 증명을 가진 사용자가 로그인할 수 없는지 여기서 확인하고 싶습니다.그러나 401 상태의 Response Entity 대신 예외가 발생했습니다.

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: cannot retry due to server authentication, in streaming mode; nested exception is java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:228)
    at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.read(MappingJackson2HttpMessageConverter.java:220)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:95)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:795)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:779)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:559)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:512)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:454)
    at cz.angular.security.basic.rest.AuthorizeControllerTest.userWithWrongCreditials(AuthorizeControllerTest.java:64)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
    at org.junit.runners.Suite.runChild(Suite.java:127)
    at org.junit.runners.Suite.runChild(Suite.java:26)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1280)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
    at org.springframework.http.client.SimpleClientHttpResponse.getRawStatusCode(SimpleClientHttpResponse.java:48)
    at org.springframework.http.client.AbstractClientHttpResponse.getStatusCode(AbstractClientHttpResponse.java:33)
    at org.springframework.web.client.DefaultResponseErrorHandler.getHttpStatusCode(DefaultResponseErrorHandler.java:56)
    at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:50)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:552)
    ... 42 more

내부적으로 스프링은 org.spring 프레임워크를 던집니다.보안.인증잘못된 자격 증명예외이지만 실제 애플리케이션 사용에서는 json 응답으로 변환됩니다.

컬을 사용했을 때 정상적인 반응이 나왔습니다.

curl -H "Content-Type: application/json" -d '{"name":"user","password":"password-wrong"}' http://localhost:8080/login
{"timestamp":"2014-12-07T10:07:27.166+0000","status":401,"error":"Unauthorized","exception":"org.springframework.security.authentication.BadCredentialsException","message":"Bad credentials","path":"/login"}

테스트 코드는 다음과 같습니다.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:9999")
public class AuthorizeControllerTest {

  public static final String LOCALHOST = "http://localhost:9999";

...

  @Test
  public void userWithWrongCreditials() throws Exception {
    RestTemplate rest = new TestRestTemplate();

    Credentials credentials = new Credentials();
    credentials.setName("user");
    credentials.setPassword("password-wrong");

    ResponseEntity<Map> response =
      rest.exchange(
        LOCALHOST + "/login",
        HttpMethod.POST,
        new HttpEntity<Credentials>(credentials),
        Map.class);

    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
  }
}

전체 프로젝트를 리포지토리에서 볼 수 있습니다.

https://bitbucket.org/winsik/security-token-stackoverflow/

인증 컨트롤러 테스트에서 합격 테스트와 불합격 테스트를 모두 볼 수 있습니다.

내용 유형 설정 등 여러 가지 시도를 해봤지만 실패했습니다.어떤 아이디어라도 주시면 감사하겠습니다.

Apache HTTP 클라이언트가 직접 오류를 처리할 수 있어야 합니다.TestRestTemplate이것은 당신의 프로젝트에서 저에게 효과가 있었습니다.

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <scope>test</scope>
    </dependency>

(또한 중복된 junit, mockito 및 spring-test 종속성도 제거했습니다.)

잭슨이 JSON을 어떻게 변환해야 할지 모를 것 같습니다.Object.해라Map아니면 뭔가?

이것으로 저의 문제가 해결되었습니다.

참조: https://github.com/spring-projects/spring-framework/issues/21321

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());   

      restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
       public boolean hasError(ClientHttpResponse response) throws IOException{
           HttpStatus statusCode = response.getStatusCode(); 
           return statusCode.series() == HttpStatus.Series.SERVER_ERROR; 
       }
     });

언급URL : https://stackoverflow.com/questions/27341604/exception-when-using-testresttemplate

반응형