Search code examples
javajunitmockmvcweb-api-testing

JUnit Testing POST to a parameterized API


How can I pass {service} to this JUnit test?

@Test
public void test4() throws Exception {
    List<ProofOfDeliveryUndeliveredResult> returnList = new ArrayList<ProofOfDeliveryUndeliveredResult>();
    given(undeliveredQueryManager.prepareUndeliverServiceRecords(isA(UndeliveredRetrieveFilters.class),isA(String.class))).willReturn(ResponseEntity.ok().body(returnList));
    String response = server.perform(MockMvcRequestBuilders.post("/api/{service}/retrieve").contentType(MediaType.APPLICATION_JSON).content("{\"startRetrieveTime\":\"\",\"endRetrieveTime\":\"\",\"timeStampFormat\":\"\"}"))
        .andExpect(status().isOk())
        .andReturn()
        .getResponse()
        .getContentAsString();
    assertEquals(response,"[]"); 
}

Solution

  • The post() method of MockMvcRequestBuilders allows you to pass a variable list of parameters, see the javadoc. The provided parameters are replaced into the URL in order.

    server.perform(
      MockMvcRequestBuilders
        .post("/api/{service}/retrieve", "someservice")
        .contentType(MediaTy...