Spring MockMvc传递嵌套表单参数

时间:2014-04-14 00:53:42

标签: spring spring-test spring-test-mvc

我有以下表格

public class MyForm {
private Account account;
}

public class Account {
private String firstName;
}

如何传递firstName参数? (以下方法不起作用)

mockMvc.perform(post("/xyz")
                .param("account.firstName", "John"))
                .andExpect(model().hasErrors())
                .andExpect(view().name("/xyz"))
                .andExpect(status().isOk())

1 个答案:

答案 0 :(得分:0)

最后我解决了这个问题。由于我使用独立设置,我必须定义验证器和消息源。

void setupTest() {
        MockitoAnnotations.initMocks(this)

        this.mockMvc = MockMvcBuilders.standaloneSetup(getController())
                .setValidator(getValidator())
                .alwaysDo(MockMvcResultHandlers.print())
                .build()
    }

    private MessageSource getMessageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

        messageSource.setBasename("messages");
        messageSource.setUseCodeAsDefaultMessage(true);

        return messageSource;
    }

    private LocalValidatorFactoryBean getValidator() {
        def validator = new LocalValidatorFactoryBean()
        validator.setValidationMessageSource(getMessageSource());

        return validator;
    }