我想在表单上的另一个对象中发送一个列表。在这种情况下,它是具有角色列表的用户。 在表单上,我有一个选择多个发送角色ID列表。 我有一个带有RoleFormatter的自定义FormatterRegistrar。这是我的代码:
我的模特:
memcached.set("foo", "bar", () => { /* this is never called */ });
memcached.setAsync("foo", "bar").then(() => { /* this is never called, either */ })
我的控制器:
@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
}
我的测试:
@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";
}
}
通过这个测试,我总是得到空角色。如何提交ID列表?如何发送清单?
答案 0 :(得分:0)
这个答案可能有点太晚了,但我最近找到了解决这个问题的方法。
我遇到了同样的问题并搜索了不同的博客,我找到了这个库:https://github.com/f-lopes/spring-mvc-test-utils
只需在项目和用户测试中导入库,就必须这样做:
//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()));