1

我想在表单上的另一个对象内发送一个列表。在这种情况下,它是具有角色列表的用户。在表单上,​​我有一个选择多个发送角色 ID 列表。我有一个带有 RoleFormatter 的自定义 FormatterRegistrar。这是我的代码:

我的模型:

@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";
    }

}

我的测试:

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()));
    }
}

通过这个测试,我总是得到空角色。如何提交 id 列表?如何发送列表?

4

1 回答 1

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()));
于 2017-09-15T00:06:39.877 回答