我要根据以下代码部分进行单元测试:
@RequestMapping(value = "/changePass", method = RequestMethod.POST)
public ModelAndView changePass(@ModelAttribute(TAPPLICATION) AppBean applicationBean, BindingResult result, ModelMap model, Principal principal, HttpServletRequest request) throws NSException, SQLException {
// ...
if (applicationBean != null
&& applicationBean.getChangePassDto() != null
&& StringUtils.isNotEmpty(applicationBean.getChangePassDto().getNewPassword())) {
String newPassword = applicationBean.getChangePassDto().getNewPassword();
// ...
}
// ...
AppBean包含以下getter和setter:
private ChangePassDto changePassDto;
public ChangePassDto getChangePassDto() {
return changePassDto;
}
public void setChangePassDto(ChangePasswordDto changePassDto) {
this.changePassDto = changePassDto;
}
基本上,当我执行单元测试时,方法
applicationBean.getChangePassDto()
是null
,但是applicationBean
不为null。如何初始化applicationBean.getChangePassDto()
,使其不返回null
?我已经用.param
方法初始化了其他非对象参数,正如在单元测试中可以看到的那样。我还将Powermock用作单元测试框架。
请在我的单元测试中找到以下部分:
@Before
public void setup() {
request = new MockHttpServletRequest();
request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
response = new MockHttpServletResponse();
session = new MockHttpSession();
request.setSession(session);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
//Added viewResolver to prevent circular view path error
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
this.mockMvc = MockMvcBuilders.standaloneSetup(appController).setViewResolvers(viewResolver).build();
}
@Test
public void changePass_ExpectC() throws Exception {
PowerMockito.doNothing().when(passwordVal).validate(any(User.class), anyListOf(Params.class), any(Object.class),any(Errors.class));
mockMvc.perform(post("/changePass").param("userLogName", "JOHN").param("userLogged", "userLogged").param("password", "password123").param("newPassword", "newPassword123").param("confirmNewPassword", "newPassword123"))
.andExpect(view().name(Constants.DENIED))
.andExpect(status().isOk()
);
}
知道如何初始化
applicationBean.getchangePassDto()
使其不为null吗?在此先感谢您的帮助。
最佳答案
只需在ChangePassDto
中创建一个AppBean
的新实例:
public class AppBean {
private ChangePassDto changePassDto = new ChangePassDto();
public ChangePassDto getChangePassDto() {
return changePassDto;
}
public void setChangePassDto(ChangePasswordDto changePassDto) {
this.changePassDto = changePassDto;
}
// ...
}
然后,您需要使用嵌套DTO中属性的完整路径,如下所示:
mockMvc.perform(post("/changePass")
.param("changePassDto.userLogName", "JOHN")
.param("changePassDto.userLogged", "userLogged")
.param("changePassDto.password", "password123")
.param("changePassDto.newPassword", "newPassword123")
.param("changePassDto.confirmNewPassword", "newPassword123"))
.andExpect(view().name(Constants.DENIED))
.andExpect(status().isOk());