0

I want to create some tests for my Controller in Spring Boot. To be concrete I want to create a test for the processing of the form to add a new item. The item belongs to the class Drug and has a collection as a

paramater:

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "drug_pet_types", joinColumns = @JoinColumn(name = "drug_id"), inverseJoinColumns = 
@JoinColumn(name = "pet_type_id"))
private Set<PetType> petTypes;`

I also have a Validator for this form, which does not allow any empty/null fields. My question is how to assign a collection as a parameter for mockMvc.perform() method. What do i put instead of the ???????. Here is the Test:

    @Test
    void testProcessCreationFormSuccess() throws Exception {
        mockMvc.perform(post("/drugs/new")
            .param("name", "Test_Drug")
            .param("batchNumber", "255888")
            .param("expirationDate", "2023-05-10")
            .param("petTypes", "_____?????????____")
        )
            .andExpect(status().is3xxRedirection());
    }```
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
SPEED8256
  • 1
  • 1
  • Possible duplicate of [Spring MockMvc - request parameter list](https://stackoverflow.com/questions/45044021/spring-mockmvc-request-parameter-list) – Sofiane Daoud Nov 13 '19 at 02:43

2 Answers2

0

If it is a POST body, then you can create a Set of PetType objects and then convert it into JSON string using ObjectMapper

String jsonString = objectMapper().writeValueAsString(Set<PetType>);

Then use content method to pass json string

@Test
void testProcessCreationFormSuccess() throws Exception {
    mockMvc.perform(post("/drugs/new")
        .param("name", "Test_Drug")
        .param("batchNumber", "255888")
        .param("expirationDate", "2023-05-10")
        .param("petTypes", "_____?????????____")
    ).content(jsonString)
        .andExpect(status().is3xxRedirection());
}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

The .param method can accept multiple values

public MockHttpServletRequestBuilder param(String name, String... values) {

You can pass multiple values like this

.param("petTypes", "type1", "type2");

or you can pass an array

String[] typeArray = {"type1", "type2"};
...
.param("petTypes", typeArray);
Amit Phaltankar
  • 3,341
  • 2
  • 20
  • 37