我正在尝试测试以下 Spring mvc 控制器方法:
@RequestMapping(value = "/preferences/email", method = RequestMethod.POST, produces = "text/html")
public String modifyEmail(@ModelAttribute @Validated({ Validation.EmailModification.class }) EmailInfo emailInfo, BindingResult bindingResult, Model model, Locale locale) {
Member member = memberService.retrieveCurrentMember();
if (!preferencesService.isEmailAvailable(emailInfo.getEmail())) {
if (member.getEmail().equals(emailInfo.getEmail())) {
bindingResult.addError(new FieldError("emailInfo", "email", messageSource.getMessage("controller.preferences.same_email", null, locale)));
} else {
bindingResult.addError(new FieldError("emailInfo", "email", messageSource.getMessage("controller.preferences.email_already_used", null, locale)));
}
}
if (bindingResult.hasErrors()) {
model.addAttribute("emailInfo", emailInfo);
return "preferences";
}
preferencesService.modifyEmail(member, emailInfo.getEmail());
return "redirect:/preferences/email";
}
这是EmailInfo
豆:
@RooEquals
@RooJavaBean
public class EmailInfo {
@NotNull(groups = { Validation.EmailModification.class })
@Pattern(regexp = "^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)+$", groups = { Validation.EmailModification.class })
private String email;
private boolean activated;
private String token;
}
这是测试类:
@ContextConfiguration
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class PreferenceControllerTest {
@Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
@Autowired
private MemberService memberService;
@Autowired
private PreferencesService preferencesService;
@Autowired
private MemberRepository memberRepository;
@Autowired
private SigninService signinService;
@Autowired
private MessageSource messageSource;
@Before
public void setup() {
mockMvc = webAppContextSetup(ctx).build();
Member currentMember = new Member();
currentMember.setEmail("currentMember@example.com");
when(memberService.retrieveCurrentMember()).thenReturn(currentMember);
when(preferencesService.isEmailAvailable("notAvailable@example.com")).thenReturn(Boolean.FALSE);
}
@Test
public void test() throws Exception {
mockMvc.perform(post("/preferences/email")//
.param("email", "newEmail@example.com"))//
.andDo(print()).andExpect(model().attributeHasNoErrors("emailInfo", "email"));
}
@Configuration
public static class testConfiguration {
@Bean
public PreferenceController preferenceController() {
return new PreferenceController();
}
@Bean
public PreferencesService preferenceService() {
return mock(PreferencesService.class);
}
@Bean
public MemberService memberService() {
return mock(MemberService.class);
}
@Bean
public MemberRepository memberRepository() {
return mock(MemberRepository.class);
}
@Bean
public SigninService signinService() {
return mock(SigninService.class);
}
@Bean
public MessageSource messageSource() {
return mock(MessageSource.class);
}
}
}
奇怪的是,我得到以下输出:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /preferences/email
Parameters = {email=[newEmail@example.com]}
Headers = {}
Handler:
Type = com.bignibou.controller.PreferenceController
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = preferences
View = null
Attribute = emailInfo
value = com.bignibou.controller.helpers.EmailInfo@9a56c123
errors = [Field error in object 'emailInfo' on field 'email': rejected value [null]; codes []; arguments []; default message [null]]
FlashMap:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = preferences
Redirected URL = null
Cookies = []
测试因上述输出而失败,我不知道为什么。我希望测试通过,因为电子邮件地址可用。
有人可以帮忙吗?
编辑1:
以下内容也不起作用:
@Before
public void setup() {
mockMvc = webAppContextSetup(ctx).build();
Member currentMember = new Member();
currentMember.setEmail("currentMember@example.com");
when(memberService.retrieveCurrentMember()).thenReturn(currentMember);
when(preferencesService.isEmailAvailable(eq("notAvailable@example.com"))).thenReturn(Boolean.FALSE);
when(preferencesService.isEmailAvailable(eq("newEmail@example.com"))).thenReturn(Boolean.TRUE);
}
编辑 2:
我能够得到的是使用上面的编辑1加上下面的测试:
@Test
public void test() throws Exception {
mockMvc.perform(post("/preferences/email")//
.param("email", "available@example.com"))//
.andDo(print())//
.andExpect(model().attributeHasNoErrors("emailInfo"));
}