2017-05-18 85 views
0

如何使用JUnit & Spring來調用不是在spring或java(其wcf rest服務)中編寫的rest服務中的方法?測試Spring - 沒有模擬的REST API

注意:我想做HTTP-GET,所以在這裏嘲笑不是這種情況。

春讓我使用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

是什麼讓你認爲它不允許在Junit中使用RestTemplate?當然它允許。 REST的基礎是HTTP,因此使用什麼框架編寫REST服務並不重要。只要它是一個REST服務,你應該可以調用它 – pvpkiran

+0

謝謝,它的工作!請把它寫成答案。 –

+0

<@Stav>完成。你想接受它。 – pvpkiran

回答

1

RestTemplate工作在Junit的爲好。它的源代碼或測試代碼無關緊要。
REST基於HTTP,因此使用什麼框架編寫REST服務並不重要。只要它是一個REST服務,你應該可以稱之爲