我想在不同的请求时间测试该会话是否具有正确的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。是否可以测试会话属性?
答案 0 :(得分: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()));