2017-04-12 3 views
1

In meinem Frühling Controller Ich habe eine Methode, die die folgende json zurückgibt:Unit Test Spring MVC Erholung Service: Array jsonPath

[ 
    { 
    "id": 2, 
    "dto": null, 
    "user": { 
     "userId": 2, 
     "firstName": "Some", 
     "lastName": "Name", 
     "age": 100, 
     "aboutMe": "boring" 
    }, 
    "isYoung": false, 
    "isOk": false 
    } 
] 

ich einen Test für diese getter.Here zu schreiben bin versucht mein Test:

@Test 
public void getterMethod() throws Exception{ 
    mockMvc.perform(get("/path?id=1")).andExpect(status().isOk()) 
     .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 
     .andExpect(jsonPath("$[0].id", is(2))) 
     .andExpect(jsonPath("$[2].user.userId", is(2))) 
     .andExpect(jsonPath("$[2].user.firstName", is("Giorgos"))) 
     .andExpect(jsonPath("$[2].user.lastName", is("Ant"))) 
     .andExpect(jsonPath("$[3].isYoung", is(false))) 
     .andExpect(jsonPath("$[4].isOk", is(false))); 
} 

Offenbar bin ich nicht dieses Recht bekommen:

Obwohl, wenn ich den Test nur für die $ laufen [0] .id der Test bestanden. Aber für alle anderen Fälle (für das geschachtelte Benutzerobjekt und isYoung fiels und isOk) bekomme ich einen Array-Index-Ausnahmefehler.

Irgendwelche Ideen? Danke!

+1

Sollten die alle Array-Indizes 0 sein? Da nur ein Element im Test JSON? – James

Antwort

2

Sollte der Test sein:

@Test 
public void getterMethod() throws Exception{ 
    mockMvc.perform(get("/path?id=1")).andExpect(status().isOk()) 
     .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 
     .andExpect(jsonPath("$[0].id", is(2))) 
     .andExpect(jsonPath("$[0].user.userId", is(2))) 
     .andExpect(jsonPath("$[0].user.firstName", is("Some"))) 
     .andExpect(jsonPath("$[0].user.lastName", is("Name"))) 
     .andExpect(jsonPath("$[0].isYoung", is(false))) 
     .andExpect(jsonPath("$[0].isOk", is(false))); 
}