0

I am currently working on a Spring project and I want to write some tests. Unfortunately I don't know how to pass the requiered Array.
The Get Request works just fine... Here is my Code:

MainControllerTest.java

private MockMvc mockMvc;

@InjectMocks
private MainController controller;

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.standaloneSetup(controller)
            .build();
}

@Test
public void resetAll() throws Exception {

    String[] players = new String[] {"Player 1", "Player 2"};

    mockMvc.perform(
            MockMvcRequestBuilders.get("http://localhost:8443/api/reset")
    )
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().string("false"));


    mockMvc.perform(
            MockMvcRequestBuilders.post("http://localhost:8443/api/player").content(players)
    ); 
}


MainController.java

@PostMapping("/player")
public void setPlayersList(@RequestBody String[] players) {
    for(int i = 0; i<players.length; i++) {
        playersList.add(players[i]);
    }
    System.out.println(Arrays.toString(playersList.toArray()));
}
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
Manuel K.
  • 23
  • 8
  • 1
    Your method expects an integer. Why would you send an array? And why do you use a POST to GET a list of questions? Oh, and the URL is completely different, too? Post the **relevant** code. – JB Nizet Jun 29 '19 at 20:27
  • Post the code for the /api/player endpoint – Alexander Petrov Jun 29 '19 at 20:28
  • I am sorry, but now it's the right code. – Manuel K. Jun 29 '19 at 20:33
  • Your server expect a JSON document representing an array of strings, right? So you need to send a JSON doculent representing an array of strings, and set the content type to application/json. Also, drop the `http://localhost:8443`. – JB Nizet Jun 29 '19 at 20:37
  • But from the frontend it receives a normal Array in the form of: ["Player 1", "Player 2"] – Manuel K. Jun 29 '19 at 20:42
  • JB Nizet is right, you need to provide JSON as a String, not array of strings. You can use Jackson's ObjectMapper and writeValueAsString method. When you call your service from frontend your request was converted to JSON String behind the scene. Latter, Jackson library converted that JSON to you String[]. – Spasoje Petronijević Jun 29 '19 at 22:28

1 Answers1

0

Late answer is better than no answer at all. Here is code that could do the trick. Here cacheNames is Array<String> and also in Controller requested this type.

mockMvc.perform(
    MockMvcRequestBuilders.delete("/endpoint")
        .queryParams(
            LinkedMultiValueMap<String, String>()
                .apply { this.addAll(Controller.PARAMETER, parameters.toList()) }
        )
).andExpect(MockMvcResultMatchers.status().isOk)

Note for Java: .apply is the same as create an instance and then call .addAll with it.

Dracontis
  • 4,184
  • 8
  • 35
  • 50