我根据以下部分代码进行单元测试:
@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
不为空。如何初始化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()
进行初始化以使其不为空?
提前感谢您的帮助。
答案 0 :(得分:1)
只需在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());