2016-12-19 30 views
0

我正在使用MockRestServiceServer來測試我的休息結束點。我有一個單元測試在工作狀態下,當我使用使用MockRestServiceServer進行單元測試時的錯誤

mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST)) 
        .andRespond(withSuccess(response, MediaType.TEXT_PLAIN)); 

但同樣失敗,當我使用

mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST)) 
     .andRespond(withBadRequest().body("test").contentType(MediaType.TEXT_PLAIN)); 

下面是完整的代碼

@Test 
public void testPost() { 
    ClientHttpRequestFactory originalRequestFactory = restTemplate.getRequestFactory(); 
    mockServer = MockRestServiceServer.createServer(restTemplate); 

    try { 
     WebTarget target = getRootTarget("/test").path(""); 

     String payLoad = ReadFile("src/test/resources/SamplePayload.html"); 
     String response = ReadFile("src/test/resources/SampleResponse.txt"); 
     Assert.assertNotNull(payLoad); 
     Assert.assertNotNull(response); 



     final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(payLoad, "text/plain"); 

     mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST)) 


      .andRespond(withSuccess(response, MediaType.TEXT_PLAIN)); 

      final Response mockResponse = target.request().post(entity); 
      mockServer.verify(); 
      Assert.assertNotNull("Response must not be null", mockResponse.getEntity()); 
      Assert.assertEquals("Response does not have expected response code", 200, mockResponse.getStatus()); 
     } finally { 
      restTemplate.setRequestFactory(originalRequestFactory); 
     } 
    } 

    @Test 
    public void testPostWithEmptyBody() { 
     ClientHttpRequestFactory originalRequestFactory = restTemplate.getRequestFactory(); 
     mockServer = MockRestServiceServer.createServer(restTemplate); 
     try{ 
      WebTarget target = getRootTarget("/test").path(""); 
      String entityBody = new String(); 


      final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain"); 

      mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST)) 
      .andRespond(withBadRequest().body("test").contentType(MediaType.TEXT_PLAIN)); 
      final Response response = target.request().post(entity); 

      mockServer.verify(); 

      Assert.assertNotNull("Response must not be null", response.getEntity()); 

      Assert.assertEquals("Response does not have expected response code", 400, response.getStatus()); 
     }finally { 
      restTemplate.setRequestFactory(originalRequestFactory); 
     } 


    } 

target.request()後( )是功能,只是叫

resttemplate.postForEntity 

在第二個測試案例中,我期待的狀態代碼是400,但是我得到了500。任何建議?

回答

0

也許你不RestTemplate權包含了MessageConvertor解決

MediaType.TEXT_PLAIN