如何配置弹簧测试Rest模板

2022-09-03 06:50:41

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

但是我现在如何向这个预配置的TestRestTemplate添加更多配置呢?我需要配置根URI并添加拦截器。

Thisi s my JUnit Test class:

@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 ...]
}

文档指出可以使用静态@TestConfiguration类。但是在那个静态类中,我无法访问或: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);
    }

  }

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

Doc sais

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

在完整的Java代码示例中,这是什么样子的?


答案 1

我知道这是一个老问题,你现在可能已经找到了另一个解决方案。但无论如何,我正在为像我一样偶然发现它的人回答。我遇到了类似的问题,最终在我的测试类中使用@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
        }
    }

答案 2

为了配置您的TestRestTemplate,官方文档建议您使用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...