Search code examples
javarestjunitjunit4

How to unit test an endpoint that accepts list of id's in a path variable?


Problem

I have an endpoint that accepts a list of ids in a path variable and I am unable to pass input in the unit test.

I know the input will be of the form

Can anyone guide me what I am doing wrong? Thanks in advance.

Below is my code

@GetMapping("/{noteIds}")
public String getNotes(
        @PathVariable List<String> noteIds) {
    String methodName = "getNotes";
return "hello";
}

Junit for the same

mockMvc.perform(get("/{noteIds}", Arrays.asList("123","145"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andDo(MockMvcResultHandlers.print());

Expected Input

localhost:port/1,2,3,4 (I am passing like this in the unit test)

Expected Output

Success

Actual Output

Bad Format Exception


Solution

  • You are passing wrong input to the endpoint. instead of passing /{noteIds} you should pass /123,145

    for example:

    mockMvc.perform(get("/123,145")
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andDo(MockMvcResultHandlers.print());