简体   繁体   中英

Send list to controller with MockMvc

I want to send a list inside another object on a form. In this case it is a user with a list of roles. On the form I have a select multiple sending a list of roles ids. I have a custom FormatterRegistrar with a RoleFormatter. This is my code:

My model:

@Entity
@Table(name = "USER")
@SequenceGenerator(name = "user_seq", sequenceName = "user_seq", initialValue = 1)
public class User implements Serializable {

    @Id
    @GeneratedValue(generator = "user_seq", strategy = GenerationType.SEQUENCE)
    private Long id;

    @NotEmpty
    @Size(min = 1, max = 50)
    @Column(name = "codigo", nullable = false)
    private String codigo;

    @Size(min = 3, max = 50)
    @Column(name = "name")
    private String name;

    ....

    @NotNull
    @NotEmpty
    @ManyToMany
    @JoinTable(name = "user_roles",
        joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") },
        inverseJoinColumns = { @JoinColumn(name = "role_id", referencedColumnName = "id") }
    )
    private Set<Role> roles = new HashSet<>();  


    //getters & setters
}

My controller:

@Controller
@SessionAttributes("user)
@RequestMapping(value = "/users")
public class UserController {

    @PreAuthorize("hasAuthority('users.admin')")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String save(@Valid @ModelAttribute User user, BindingResult result, SessionStatus status, RedirectAttributes ra,
            HttpServletRequest request) {

        //Save user

        return "detail";
    }

}

My test:

public class UserControllerTest {

    @Mock
    private UserService userService;

    @InjectMocks
    private UserController userController;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        // Process mock annotations
        MockitoAnnotations.initMocks(this);

        // Setup Spring test in standalone mode
        this.mockMvc = MockMvcBuilders.standaloneSetup(userController)
                .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver()).build();
    }


    @Test
    public void testSave() throws Exception {
        User user = new User();

        // Without errors
        this.mockMvc.perform(post("/users/update")
                .param("id", "1")
                .param("name", "Jonh")
                .param("roles.id", "1", "2")
                .sessionAttr("user", user))
                .andExpect(view().name("detail"))
                .andExpect(model().hasNoErrors()));
    }
}

With this test I always get null roles. How do I submit a list of ids? how send a list?

This answer might be a little bit too late, but I recently found a solution for this problem.

I was going through the same problem and searching through different blogs, I found this library: https://github.com/f-lopes/spring-mvc-test-utils

Just import the library in your project and in your user test, you have to do this:

//here, the method might be called 'save' or 'update'. You just put in there the name of the method for updating a user
doNothing().when(userService).save(any(User.class));

User user = new User();
//set user's properties
user.setRoles(Arrays.asList(
    new Role(), //here you set role's properties
    new Role() //here as well
));

//here comes the magic
mockMvc.perform(postForm("/users/update", user))
       .andExpect(view().name("detail"))
       .andExpect(model().hasNoErrors()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM