java在没有模拟的情况下测试Spring REST API
如何使用JUnit&;春天
注意:我想做HTTP-GET,所以这里没有模拟
Spring允许我使用JUnit中的restTemplate.getForObject(..)
?黄瓜
到目前为止,我有一个使用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
};
}
}
我想让我的测试看起来:
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);
}
}
# 1 楼答案
RestTemplate也适用于Junit。不管是源代码还是测试代码
REST是基于HTTP的,所以使用什么框架来编写REST服务并不重要。只要是休息服务,你就可以打电话给它