2016-11-21 170 views
1

我實現了基於Jersey的REST風格的Web服務。 當發送我的請求時,我首先檢查是否定義了一些必需的參數,如果沒有,我將返回帶有錯誤代碼和錯誤消息的響應。 下面是摘錄:無法從http請求中獲取JSON

@Path("/groups") 
@RequestScoped 
@Consumes(MediaType.APPLICATION_JSON) 
@Produces(value = {MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) 
public class GroupResource 
{ 
    ... 
    @POST 
    public Response createGroup(Group group, @Context UriInfo uriInfo) 
    { 
    logger.info("-------------------"); 
    logger.info("Create group"); 
    logger.fine(group.toString()); 
    logger.info("-------------------"); 

    // check mandatory fields 
    if (!checkMandatoryFields(group, errorMessages)) 
    { 
     return Response.status(Status.BAD_REQUEST).entity(errorMessages).build(); 
    } 
    ... 
} 

然後我實現了一個JUnit測試來測試它:

@Test 
    public void testCreateGroup() 
    { 
    try 
    { 
     URL url = new URL(URL_GROUPS_WS); 

     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/json"); 

     String json2send = "{\"grid\":\"1\", \"gidNumber\":\"2\", \"groupName\":\"TestGroup\", \"groupDescription\":\"Initial description\", \"targetSystems\":[\"ADD TS1\"]}"; 

     OutputStream os = conn.getOutputStream(); 
     os.write(json2send.getBytes()); 
     os.flush(); 

     System.out.println("XXXXXXXX Sending request XXXXXXXX \n"); 

     if (conn.getResponseCode() != 200) 
     { 
     BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

     StringBuffer error = new StringBuffer(); 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
     { 
      error.append(inputLine); 
     } 

     in.close(); 

     throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + error.toString()); 
     } 
    ... 
} 

我的問題是,我得到的responseCode,但我不知道怎麼弄的錯誤消息,應該在響應中的某個地方,對嗎? (Response.status(Status.BAD_REQUEST).entity(**errorMessages**).build())。

上面的代碼,在那裏我檢查響應代碼,不工作...

你能幫幫我嗎?

+0

定義 「不工作」 精確。你期望發生什麼,魔杖會發生什麼呢? –

回答

0

相反InputStream的使用ErrorStream -

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream())); 

ErrorStream會給你在錯誤的情況下的響應。

0

這不是如何正確測試球衣組件,你確實應該依靠Jersey Test Framework測試一個組成部分,它隱藏了許多複雜性,使得單元測試是很容易閱讀和維護。

您目前的代碼是太容易出錯,應該避免

假設您使用的是maven,則需要使用test作用域將下2個依賴項添加到項目中。

<dependency> 
    <groupId>org.glassfish.jersey.test-framework</groupId> 
    <artifactId>jersey-test-framework-core</artifactId> 
    <version>2.24</version> 
    <scope>test</scope> 
</dependency> 
<dependency> 
    <groupId>org.glassfish.jersey.test-framework.providers</groupId> 
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId> 
    <version>2.24</version> 
    <scope>test</scope> 
</dependency> 

然後,你可以簡單地讓你的單元測試擴展JerseyTest和覆蓋的方法configure提供一流的其餘部分的,它是對環境的設置完成。它會自動啓動一個灰熊服務器併爲你綁定你的組件,所以唯一要做的就是編寫你的單元測試。

你的測試類可能是類似的東西:

public class GroupResourceTest extends JerseyTest { 

    @Override 
    protected Application configure() { 
     return new ResourceConfig(GroupResource.class); 
    } 

    @Test 
    public void testCreateGroup() { 
     Group group = // create your group instance to test here 
     Response response = target("/groups") 
      .request() 
      .accept(MediaType.APPLICATION_JSON) 
      .post(Entity.entity(group, MediaType.APPLICATION_JSON)); 
     Assert.assertEquals(Response.Status.BAD_REQUEST, response.getStatus()); 
     Assert.assertEquals("My error message", response.readEntity(String.class)); 
    } 
}