user3318489 user3318489 - 1 year ago 67
Java Question

RESTful Services test with RestTemplate

In my application I have a lot of REST- Services. I have written tests for all services with:


A REST- Service invokation e.g. looks like this:

final String loginResponse ="http://localhost:8080/api/v1/xy", HttpMethod.POST, httpEntity, String.class)

and I check the response body afterwards - all works fine.
The disadvantage is, that the application for sure must be started in order to invoke the REST- Services.

My question now would be how I can do this in my JUnit- @Test methods?
It is a Spring Boot application (with embedded tomcat).

Thanks for help!

Answer Source

There's a good chapter on this in the documentation, I suggest you read through it to fully understand what you can do.

I like to use @IntegrationTest with a custom configuration since that starts up the entire server and lets you test the complete system. If you want to replace certain parts of the system with mocks you can do that by excluding certain configurations or beans and replacing them with your own.

Here's a small example. I've left out the MessageService interface because it's obvious from IndexController what it does, and it's default implementation - DefaultMessageService - because it's not relevant.

What it does is that it spins up the entire application minus the DefaultMessageService but with it's own MessageService instead. It then uses RestTemplate to issue real HTTP requests to the running application in the test case.

Application classes:

public class IntegrationTestDemo {

    public static void main(String[] args) {, args);


public class IndexController {

    MessageService messageService;

    String getMessage() {
        return messageService.getMessage();

Test classes:

@SpringApplicationConfiguration(classes = TestConfig.class)
@WebIntegrationTest // This will start the server on a random port
public class IntegrationTestDemoTest {

    // This will hold the port number the server was started on
    int port;

    final RestTemplate template = new RestTemplate();

    public void testGetMessage() {
        String message = template.getForObject("http://localhost:" + port + "/", String.class);

        Assert.assertEquals("This is a test message", message);

    excludeFilters = {
        // Exclude the default message service
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = DefaultMessageService.class),
        // Exclude the default boot application or it's
        // @ComponentScan will pull in the default message service
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = IntegrationTestDemo.class)
public class TestConfig {

    // Define our own test message service
    MessageService mockMessageService() {
        return new MessageService() {
            public String getMessage() {
                return "This is a test message";