如何配置Spring TestRestTemplate

问题描述 投票:6回答:3

我有一个REST(spring-hateoas)服务器,我想用JUnit测试来测试。因此我使用自动注射的TestRestTemplate

但是,我现在如何为此预先配置的TestRestTemplate添加更多配置?我需要配置rootURI并添加拦截器。

这是我的JUnit Test类:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)      

public class RestEndpointTests {
  private Logger log = LoggerFactory.getLogger(this.getClass());

  @LocalServerPort
  int localServerPort;

  @Value(value = "${spring.data.rest.base-path}")   // nice trick to get basePath from application.properties
  String basePath;

  @Autowired
  TestRestTemplate client;    //  how to configure client?

  [... here are my @Test methods that use client ...]
}

The documentation sais that a static @TestConfiguration class can be used.但在静态类中我无法访问localServerPortbasePath

  @TestConfiguration
  static class Config {

    @Bean
    public RestTemplateBuilder restTemplateBuilder() {
      String rootUri = "http://localhost:"+localServerPort+basePath;    // <=== DOES NOT WORK
      log.trace("Creating and configuring RestTemplate for "+rootUri);
      return new RestTemplateBuilder()
        .basicAuthorization(TestFixtures.USER1_EMAIL, TestFixtures.USER1_PWD)
        .errorHandler(new LiquidoTestErrorHandler())
        .requestFactory(new HttpComponentsClientHttpRequestFactory())
        .additionalInterceptors(new LogRequestInterceptor())
        .rootUri(rootUri);
    }

  }

我最重要的问题:为什么TestRestTemplate首先不考虑spring.data.rest.base-pathapplication.properties?是不是完全预配置的想法,这个包装类的整个用例?

医生知道

如果您正在使用@SpringBootTest注释,TestRestTemplate将自动可用,并且可以@Autowired到您的测试中。如果需要自定义(例如添加其他消息转换器),请使用RestTemplateBuilder @Bean。

在完整的Java代码示例中,它看起来如何?

java spring rest spring-data-rest
3个回答
11
投票

我知道这是一个老问题,你现在可能已经找到了另一个解决方案。但无论如何,我正在回答其他人像我一样磕磕绊绊。我有一个类似的问题,最后在我的测试类中使用@PostConstruct来构造一个配置为我喜欢的TestRestTemplate而不是使用@TestConfiguration。

    @RunWith(SpringJUnit4ClassRunner.class)
    @EnableAutoConfiguration
    @SpringBootTest(classes = {BackendApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class MyCookieClientTest {
        @LocalServerPort
        int localPort;

        @Autowired
        RestTemplateBuilder restTemplateBuilder;

        private TestRestTemplate template;

        @PostConstruct
        public void initialize() {
            RestTemplate customTemplate = restTemplateBuilder
                .rootUri("http://localhost:"+localPort)
                ....
                .build();
            this.template = new TestRestTemplate(customTemplate,
                 null, null, //I don't use basic auth, if you do you can set user, pass here
                 HttpClientOption.ENABLE_COOKIES); // I needed cookie support in this particular test, you may not have this need
        }
    }

0
投票

为了配置TestRestTemplate,官方documentation建议您使用TestRestTemplate,如下例所示(例如,添加基本身份验证):

public class YourEndpointClassTest {
    private static final Logger logger = LoggerFactory.getLogger(YourEndpointClassTest.class);  

    private static final String BASE_URL = "/your/base/url";

    @TestConfiguration
    static class TestRestTemplateAuthenticationConfiguration {

        @Value("${spring.security.user.name}")
        private String userName;

        @Value("${spring.security.user.password}")
        private String password;

        @Bean
        public RestTemplateBuilder restTemplateBuilder() {
            return new RestTemplateBuilder().basicAuthentication(userName, password);
        }
    }


    @Autowired
    private TestRestTemplate restTemplate;

//here add your tests...

0
投票

当我需要在我们的测试环境中使用TestRestTemplate访问远程服务器上的REST端点时,我遇到了这种情况。因此,测试没有启动Spring Boot应用程序,而是仅连接到远程端点并从那里使用REST服务。测试的配置更简单,执行速度更快,因为它没有构建复杂的Spring(Boot)上下文。以下是我配置的摘录:

@RunWith(SpringRunner.class)
public class RemoteRestTestAbstract {

protected TestRestTemplate restTemplate;
private static RestTemplateBuilder restTemplateBuilder;


@BeforeClass
public static void setUpClass() {
    restTemplateBuilder = new RestTemplateBuilder()
        .rootUri("http://my-remote-test-server.my-domain.com:8080/");
}

@Before
public void init() {
    restTemplate = new TestRestTemplate(restTemplateBuilder);
    login();
}

//...

}
© www.soinside.com 2019 - 2024. All rights reserved.