【问题标题】:How can i test existence specific data in session?我如何测试会话中存在的特定数据?
【发布时间】:2015-09-23 06:17:50
【问题描述】:

我想测试该会话在不同的请求时间是否具有正确的 TTL 值。我该怎么做?

@ThreadSafe
@RestController
@SessionAttributes("TTL")
@RequestMapping("/rest/")
public class MessageRestController {
    private static final String TTL = "TTL";

    @Secured("ROLE_USER")
    @RequestMapping("/message")
    public List<String> getMessage(Model model) {
        final Optional<String> message = messageService.getMessage();
        if (message.isPresent()) {
            return Collections.singletonList(message.get());
        } else {
            final Long currentTtl = (Long) model.asMap().get(TTL);
            if (currentTtl == null || Instant.ofEpochMilli(currentTtl).isBefore(Instant.now())) {
                messageService.generateNewMessage();
                model.addAttribute(TTL, Instant.now().plusMillis(ttl).toEpochMilli());
            }

            return Collections.emptyList();
        }
    }
}

我试着这样做

    mockMvc.perform(get("/rest/message").sessionAttr("TTL", Instant.now().minusSeconds(60).toEpochMilli()))
            .andExpect(status().isOk())
            .andExpect(model().attribute("TTL", Matchers.greaterThan(Instant.now().toEpochMilli())));

它抛出异常java.lang.AssertionError: No ModelAndView found。事实上,我没有 ModelAndView。是否可以测试会话属性?

【问题讨论】:

    标签: java spring-mvc session spring-test-mvc


    【解决方案1】:

    可以这样测试

    MockHttpSession session = new MockHttpSession();
        session.putValue("TTL", Instant.now().minusSeconds(60).toEpochMilli());
    
    mockMvc.perform(get("/rest/message").session(session))
            .andExpect(status().isOk());
    
    assertThat((Long) session.getAttribute("TTL"), Matchers.greaterThan(Instant.now().toEpochMilli()));
    

    【讨论】:

      猜你喜欢
      • 2012-10-19
      • 2012-11-03
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2019-05-12
      相关资源
      最近更新 更多