我在为测试设置会话属性时遇到问题。我正在使用 MockMvc 来测试对控制器的调用。会话模型上有一个成员属性(代表已登录的人)。SessionModel 对象作为会话属性添加。我期待它在 ModelMap 参数中填充到下面的 formBacking 方法,但 ModelMap 始终为空。
控制器代码在通过 webapp 运行时可以正常工作,但在 JUnit 中则不行。知道我做错了什么吗?
这是我的 JUnit 测试
@Test
public void testUnitCreatePostSuccess() throws Exception {
UnitCreateModel expected = new UnitCreateModel();
expected.reset();
expected.getUnit().setName("Bob");
SessionModel sm = new SessionModel();
sm.setMember(getDefaultMember());
this.mockMvc.perform(
post("/units/create")
.param("unit.name", "Bob")
.sessionAttr(SessionModel.KEY, sm))
.andExpect(status().isOk())
.andExpect(model().attribute("unitCreateModel", expected))
.andExpect(view().name("tiles.content.unit.create"));
}
这是有问题的控制器
@Controller
@SessionAttributes({ SessionModel.KEY, UnitCreateModel.KEY })
@RequestMapping("/units")
public class UnitCreateController extends ABaseController {
private static final String CREATE = "tiles.content.unit.create";
@Autowired
private IUnitMemberService unitMemberService;
@Autowired
private IUnitService unitService;
@ModelAttribute
public void formBacking(ModelMap model) {
SessionModel instanceSessionModel = new SessionModel();
instanceSessionModel.retrieveOrCreate(model);
UnitCreateModel instanceModel = new UnitCreateModel();
instanceModel.retrieveOrCreate(model);
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String onCreate(
@ModelAttribute(UnitCreateModel.KEY) UnitCreateModel model,
@ModelAttribute(SessionModel.KEY) SessionModel sessionModel) {
model.reset();
return CREATE;
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String onCreatePost(
@ModelAttribute(SessionModel.KEY) SessionModel sessionModel,
@Valid @ModelAttribute(UnitCreateModel.KEY) UnitCreateModel model,
BindingResult result) throws ServiceRecoverableException {
if (result.hasErrors()){
return CREATE;
}
long memberId = sessionModel.getMember().getId();
long unitId = unitService.create(model.getUnit());
unitMemberService.addMemberToUnit(memberId, unitId, true);
return CREATE;
}
}