我如何测试会话中存在的特定数据?

How can i test existence specific data in session?

我想测试会话在不同的请求时间上是否具有正确的 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。是否可以测试会话属性?

可以这样测试

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()));