0

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

4

1 回答 1

0

可以这样测试

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()));
于 2015-09-23T06:30:48.917 回答