【问题标题】:Configure TestRestTemplate bean with proper root url in Spring Boot MVC Integration Test在 Spring Boot MVC 集成测试中使用正确的根 url 配置 TestRestTemplate bean
【发布时间】:2019-12-02 16:43:41
【问题描述】:

我想在 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】:

    是的。你需要提供一个@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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2019-03-07
      • 1970-01-01
      • 2015-06-14
      • 2019-02-25
      • 2019-01-14
      • 2021-01-24
      • 2020-06-22
      • 2017-06-21
      相关资源
      最近更新 更多