2013-07-12 20 views
0

我們必須用jUnit測試我們的JavaEEServer。出於這個原因,我們想測試我們的REST get方法。我們用Jersey框架實現了這些方法。出於這個原因,這些方法返回類型爲java.ws.rs.core.Response的響應。將java.ws.rs.core.Response轉換爲JSON以進行jUnit測試

如何將這些響應轉換爲JSON,當我們想從服務器端進行測試時,只需要直接調用方法?

例子:

@GET 
@Path("getallemployees") 
@Produces("application/json") 
public Response getAllEmployees() { 
    //here we create a generic entity (this works) 
    return Response.ok(entity).build(); 
} 

我們需要測試什麼:

@Test 
public void testgetAllEmployees() { 
    // here we initialize the mocked database content (Mockito) 
    Response test = employeeResource.getAllEmployees(); 
    // here we want to have the Response as JSON 
} 

謝謝!

+0

'test.getEntity()'給你什麼? – Thilo

+0

我們從EmployeeResource類型(我們的getMethod所在的位置)中獲得一個對象,並且我們有一個ArrayList,其中包含我們想要的JSON字符串中的內容,但是我們無法獲取此JSON字符串。如果我們做'test.getEntity()。toString()',那麼我們得到:'com.ourcompany.restserver.EmployeeResource $ 1 @ 788ab708' – tralala

+0

只是一個快速的建議:getAllEmployees返回特定的EmployeesEntity而不是響應。在這種情況下,它將清楚應該預期什麼樣的響應(與通用響應相對),並且代碼將更加簡潔(返回新的EmployeesEntity(employeesList))。 – Jonas

回答

0

它看起來像你試圖混合單元和集成測試,你應該選擇一個。

如果你對特定的資源實現感興趣,你應該使用單元測試,因此不關心JSON輸出。只是模擬資源依賴關係,請致電getAllEmployees()並確認期望值。

但是,如果你有興趣在服務輸出,那麼你或許應該推出集成系統(可能使用Jetty作爲一個獨立的容器中,並在內存中,如果一個需要數據庫),並使用Jersey Client測試響應:

Client client = ClientBuilder.newClient(); 
WebTarget webTarget = client.target("http://example.com/rest").path("getallemployees"); 
String rawResponseBody = webTarget.request(MediaType.APPLICATION_JSON).get(String.class); 

根據我的經驗,很少使用原始響應。您可能會使用實體類而不是String