猿问

如何在 MockMVC 帖子中将对象传递给 ModelAttrbiute?

用户模型:


@Entity

@Table(name="user")

public class User {


@Id @GeneratedValue(strategy=GenerationType.IDENTITY)

private Integer id;


@NotBlank

@Column(name="username")

private String username;


@NotEmpty

@ManyToMany(fetch = FetchType.EAGER)

@JoinTable(name="user_role", joinColumns = {@JoinColumn(name="user_id")},

                             inverseJoinColumns = {@JoinColumn(name="role_id")})

private Set<Role> roles;

}

控制器:


@RequestMapping(value = {"/users/edit/{id}"}, method = RequestMethod.POST)

public String editUser(ModelMap model, @Valid @ModelAttribute("user") User user, BindingResult result) {


    if(result.hasErrors()) {

        return "AddUserView";

    }


    return "redirect:/users";

}

用 MockMVC 测试:


@Test

public void performUpdateUserTest() throws Throwable {

            mockMvc.perform(post("/users/edit/{id}", user.getId())

                   .param("username", "User"));

}

好吧,我可以像往常一样使用param()传递一个 param username。但是我应该怎么处理ROLES呢?该字段是一个单独的对象。我无法使用param()传递它。那怎么可能在测试中通过呢?


我发现的唯一出路是创建一个实体并使用.flashAttr()传递它:


    @Test

    public void performUpdateUserTest() throws Throwable {

          User user = new User("User", new HashSet<Role>(Arrays.asList(new Role("USER"))));

          mockMvc.perform(post("/users/edit/{id}", user.getId())

                 .flashAttr("user", user));

    }

但是,如果我需要测试由于ROLES字段中的绑定错误而无法更新用户(ROLES 不能为 null,假设它被设置为 null)怎么办?因此,我无法创建用户(并将其与 .flashAttr 一起使用)已经绑定错误,因为将抛出异常。而且还是要分开传。


一只甜甜圈
浏览 260回答 1
1回答

叮当猫咪

好吧,经过长时间的搜索,我发现我应该在MockMVC中添加一个转换器。例如,您可以在此处阅读什么转换器。我的项目中已经有了它,但没有意识到它不适用于 MockMVC。因此,您可以像这样将转换器添加到 MockMVC:&nbsp; &nbsp; @Autowired&nbsp; &nbsp; private StringToRoleConverter stringToRoleConverter;&nbsp; &nbsp; @Before&nbsp; &nbsp; public void init() {&nbsp; &nbsp; &nbsp; &nbsp; FormattingConversionService cs = new FormattingConversionService();&nbsp; &nbsp; &nbsp; &nbsp; cs.addConverter(stringToRoleConverter);&nbsp; &nbsp; &nbsp; &nbsp; mockMvc = MockMvcBuilders.standaloneSetup(userController)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .setConversionService(cs)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .build();&nbsp; &nbsp; }转换器本身:@Componentpublic class StringToRoleConverter implements Converter<String, Role> {&nbsp; &nbsp; @Autowired&nbsp; &nbsp; private RoleService roleService;&nbsp; &nbsp; @Override&nbsp; &nbsp; public Role convert(String id) {&nbsp; &nbsp; &nbsp; &nbsp; Role role = roleService.findById(Integer.valueOf(id));&nbsp; &nbsp; &nbsp; &nbsp; return role;&nbsp; &nbsp; }}然后我可以添加这样的参数:mockMvc.perform(post("/users/edit/{id}", user.getId())&nbsp; &nbsp; &nbsp; &nbsp; .param("roles", "2"))尽管我在那里传递了一个字符串,但它将在 Spring 转换器的帮助下转换为 Role。
随时随地看视频慕课网APP

相关分类

Java
我要回答