Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to test my REST endpoints with a TestRestTemplate in a Spring Boot integration test but I don't want to write "http://localhost" + serverPort + "/" as prefix for each request all the time. Can Spring configure a TestRestTemplate-bean with the proper root url and autowire it into my tests?

I don't want it to look like that:

@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);
    }

}
like image 235
phip1611 Avatar asked Dec 14 '25 04:12

phip1611


1 Answers

Yes. You need to provide a @TestConfiguration that registers a configured TestRestTemplate-bean. Then you can @Autowire this bean into your @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);
    }
}
like image 102
phip1611 Avatar answered Dec 16 '25 06:12

phip1611