Search code examples
javaspringrestjunitcucumber-jvm

Testing Spring - REST API without mock


How does one invoke methods in a rest service that is not written in spring or java (its wcf rest service) using JUnit & Spring?

Note: I want to do HTTP-GET so mocking is not the case here.

Does Spring let me use restTemplate.getForObject(..) from JUnit? Cucumber?


So far I have a client written using Spring:

@SpringBootApplication
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);
    private static final String SERVICE_URL="http://localhost:12345/PrivilegesService/IsAlive";


    public static void main(String args[]) {
        SpringApplication.run(Application.class);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        return args -> {
            boolean response = restTemplate.getForObject(SERVICE_URL, boolean.class);
            log.info("response: "+ response); // print : true
        };
    }
}

I want my tests look :

public class StepDefinitions {

    @When("^application is up$")
    public void the_client_issues_GET_version(){

    }
    @Then("^the server should be running$")
    public void the_client_receives_status_code_of()  {
        boolean response = restTemplate.getForObject(SERVICE_URL, boolean.class);
        AssertTrue(true,response);
    }
}

Solution

  • RestTemplate works in Junit as well. It doesn't matter if its a source code or test code.
    REST is based on HTTP, so it doesn't matter what framework is used to write a REST service. As long as it is a REST service, you should be able to call it