在Spring Boot MVC集成测试中使用正确的根URL配置TestRestTemplate bean

问题描述 投票:0回答:1

我想在Spring Boot集成测试中使用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);
    }

}
spring-boot integration-testing spring-test
1个回答
0
投票

是。您需要提供一个@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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.