在 Spring 引导 MVC 集成测试中使用适当的根 url 配置 TestRestTemplate bean

Configure TestRestTemplate bean with proper root url in Spring Boot MVC Integration Test

我想在 Spring 启动集成测试中使用 TestRestTemplate 测试我的 REST 端点,但我不想一直将 "http://localhost" + serverPort + "/" 作为每个请求的前缀. Spring 可以使用正确的根 url 配置一个 TestRestTemplate-bean 并将其自动装配到我的测试中吗?

我不希望它看起来像那样:

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

    @LocalServerPort
    private int port;

    private TestRestTemplate testRestTemplate = new TestRestTemplate();

    @Test()
    public void test1() {
        // out of the box I have to do it like this:
        testRestTemplate.getForEntity("http://localhost:" + port + "/my-endpoint", Object.class);

        // I want to do it like that
        //testRestTemplate.getForEntity("/my-endpoint", Object.class);
    }

}

是的。您需要提供一个 @TestConfiguration 来注册一个已配置的 TestRestTemplate-bean。然后你可以 @Autowire 这个 bean 到你的 @SpringBootTest.

TestRestTemplateTestConfiguration.java

@TestConfiguration
public class TestRestTemplateTestConfiguration {

    @LocalServerPort
    private int port;

    @Bean
    public TestRestTemplate testRestTemplate() {
        var restTemplate = new RestTemplateBuilder().rootUri("http://localhost:" + port);
        return new TestRestTemplate(restTemplate);
    }

}

FoobarIntegrationTest.java

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

    @Autowired
    private TestRestTemplate restTemplate;

    @Test()
    public void test1() {
        // works
        testRestTemplate.getForEntity("/my-endpoint", Object.class);
    }
}