[英]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. 在表单上,我有一个选择多个,用于发送角色ID列表。 I have a custom FormatterRegistrar with a RoleFormatter. 我有一个带RoleFormatter的自定义FormatterRegistrar。 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? 如何提交ID列表? 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 我遇到了同样的问题,并搜索了不同的博客,我发现了这个库: 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()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.