spring - 在 Spring 3.2 上设置 JUnit 的 session 属性

标签 spring junit spring-test-mvc

我在设置测试的 session 属性时遇到问题。我正在使用 MockMvc 来测试对 Controller 的调用。 session 模型有一个成员属性(代表已登录的人)。 SessionModel 对象作为 session 属性添加。我期望将其填充到下面的 formBacking 方法的 ModelMap 参数中,但 ModelMap 始终为空。

Controller 代码在通过 Web 应用程序运行时工作正常,但在 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

@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;
  }

}

最佳答案

为您的测试类添加 @WebAppConfiguration 注释并 Autowiring 以下内容。(WebApplicationContextMockHttpSession )

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ "classpath:springDispatcher-servlet.xml" })
public class MySessionControllerTest {
    @Autowired WebApplicationContext wac; 
    @Autowired MockHttpSession session;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testUnitCreatePostSuccess() throws Exception {
        UnitCreateModel expected = new UnitCreateModel();
        expected.reset();
        expected.getUnit().setName("Bob");

        SessionModel sm = new SessionModel();
        sm.setMember(getDefaultMember());
        session.setAttribute(SessionModel.KEY, sm);
        this.mockMvc.perform(
            post("/units/create")
            .session(session)
            .param("unit.name", "Bob")
            .andExpect(status().isOk())
            .andExpect(model().attribute("unitCreateModel", expected))
            .andExpect(view().name("tiles.content.unit.create"));

  }
}

关于spring - 在 Spring 3.2 上设置 JUnit 的 session 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14232833/

相关文章:

java - 如何将身份验证成功处理程序分配给多个 Spring Security 领域

java - 如何使用 jUnit 使用 java 配置类而不使用 XML 来测试 spring mvc 中的 DAO 实现方法

java - 在 Spring Boot 1.4 中测试安全性

java - 如何在 Intellij 中保存超过 5 个 JUnits 配置

junit - 在 Robolectric 中测试时片段 getView 返回 null

spring - 如何使用 Spring Boot 1.4.0 + 为 JUNIT 测试用例使用随机端口

unit-testing - 使用 MockMvc 和 Mockito 测试 Katharsis JsonApi

forms - Spring中的重复表单提交

java - Spring Boot 与 Hibernate : Keep Creating Database when already Exist

java - 如何在返回对象的 Spring MVC @RestController @ResponseBody 类中响应 HTTP 状态代码?