我在3.1版本中使用新的spring-test來運行集成測試。它工作得很好,但我無法讓會話正常工作。我的代碼:支持會話支持的Spring mvc 3.1集成測試
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/main/webapp")
@ContextConfiguration({"classpath:applicationContext-dataSource.xml",
"classpath:applicationContext.xml",
"classpath:applicationContext-security-roles.xml",
"classpath:applicationContext-security-web.xml",
"classpath:applicationContext-web.xml"})
public class SpringTestBase {
@Autowired
private WebApplicationContext wac;
@Autowired
private FilterChainProxy springSecurityFilterChain;
@Autowired
private SessionFactory sessionFactory;
protected MockMvc mock;
protected MockHttpSession mockSession;
@Before
public void setUp() throws Exception {
initDataSources("dataSource.properties");
mock = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
mockSession = new MockHttpSession(wac.getServletContext(), UUID.randomUUID().toString());
}
@Test
public void testLogin() throws Exception {
// this controller sets a variable in the session
mock.perform(get("/")
.session(mockSession))
.andExpect(model().attributeExists("csrf"));
// I set another variable here just to be sure
mockSession.setAttribute(CSRFHandlerInterceptor.CSRF, csrf);
// this call returns 403 instead of 200 because the session is empty...
mock.perform(post("/setup/language")
.session(mockSession)
.param(CSRFHandlerInterceptor.CSRF, csrf)
.param("language", "de"))
.andExpect(status().isOk());
}
}
我的會話在每個請求中都是空的,我不知道爲什麼。
編輯:最後斷言失敗:andExpect(status().isOk());
。它返回403而不是200.
哪個斷言失敗? –
最後一個:'andExpect(status()。isOk());'因爲我檢查會話中應該設置的變量,但會話是空的,所以它返回禁止。 – islon
另請參見[如何使用spring 3.2新的mvc測試登錄用戶](http://stackoverflow.com/questions/14308341/how-to-login-a-user-with-spring-3-2-new-mvc -testing)。 – Arjan