Java 无法从控制器中的请求获取令牌
我试图在Spring中测试loginController,但无法从请求中获取令牌。 在我的测试中Java 无法从控制器中的请求获取令牌,java,spring,token,Java,Spring,Token,我试图在Spring中测试loginController,但无法从请求中获取令牌。 在我的测试中 private CsrfToken token; HttpServletRequest request = new MockHttpServletRequest(); @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this);
private CsrfToken token;
HttpServletRequest request = new MockHttpServletRequest();
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
token = new DefaultCsrfToken("1", "a", "b");
request.setAttribute(CsrfToken.class.getName(), token);
}
@Test
public void testCtrlCorrecltyHandlesPassword() throws Exception {
CsrfToken token2 = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
MvcResult result = this.mockMvc.perform(get("/rest/login")
.param("name", name)
.param("password", password)
.param("request", request.toString())
//.sessionAttr("request", request)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
}
当我调试时,我看到token2已经成功创建,并且我从请求中获得了它的值,但当我尝试使用完全相同的方法时,它在控制器中
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
是空的
我还尝试将.sessionatrrequest、request和@ModelAttributerequestHttpServletRequest作为控制器中的参数,但不起作用 最终
MockHttpSession session = new MockHttpSession();
session.setAttribute("token", token);
MvcResult result = this.mockMvc.perform(get("/rest/login").session(session)
.header("X-Csrf-Token", "")
.requestAttr(CsrfToken.class.getName(), token)
.param("name", name)
.param("password", password)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
我更新了我的问题,以防有人能在这方面帮助我,谢谢