3

I am testing an endpoint which returns a list of objects. I am currently testing each element in sequence as per the code below. The code is abbreviated for clarity.

There may be many elements and many attributes. This code can get long and ugly

  public void testXxxOK() throws URISyntaxException, Exception {
    when(thisCall).thenReturn(mockThis());
    when(thatCall).thenReturn(mockThat());
    mockMvc
        .perform(get(relativePath(
            "/getStuffRestEndPoint?argument1=123&argument2=01-11-2001%200101Z"))
                .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk()).andExpect(content().contentType(APPLICATIONJSON))
        .andExpect(jsonPath("$.dataList", hasSize(3)))

        .andExpect(jsonPath("$.dataList[0].parameter1", is(0)))
        .andExpect(jsonPath("$.dataList[0].parameter2", is("name0")))

        .andExpect(jsonPath("$.dataList[1].parameter1", is(1)))
        .andExpect(jsonPath("$.dataList[1].parameter2", is("name0")))

        .andExpect(jsonPath("$.dataList[2].parameter1", is(2)))
        .andExpect(jsonPath("$.dataList[2].parameter2", is("name0")))

  }

Can I wrap a loop around the .andExpect() calls so that I have only 1 list of parameters? This is what I mean. How do I do this?

for (i=0; i<size; i++)
{
    .andExpect(jsonPath("$.dataList[i].parameter1", is(i)))
    .andExpect(jsonPath("$.dataList[i].parameter2", is("name0")))
}
user9993
  • 5,833
  • 11
  • 56
  • 117
mikec
  • 155
  • 1
  • 17

2 Answers2

3

There might be a way better way to do this, but off the top of my head you could also try:

when(thisCall).thenReturn(mockThis());
when(thatCall).thenReturn(mockThat());
ResultActions actions = mockMvc
    .perform(get(relativePath("/getStuffRestEndPoint?argument1=123&argument2=01-11-2001%200101Z"))
    .accept(MediaType.APPLICATION_JSON));

for (i=0; i<size; i++)
{
    actions = actions.andExpect(jsonPath("$.dataList[i].parameter1", is(i)))
    actions = actions.andExpect(jsonPath("$.dataList[i].parameter2", is("name0")))
}
jlb
  • 19,090
  • 8
  • 34
  • 65
0

It will be easier, if you first call getResult() to get result and then iterate on result to test values.

Gaurav Kumar Singh
  • 582
  • 2
  • 5
  • 14