I am playing around with Spring Security and now I am trying get some knowledge about testing my REST-controller with regards to security.
So I prepared my test-class with:
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
containing test-cases mostly of the following or similar form:
@Test
public void handleSecuredRequest_shouldReturn200_withAdminUser() throws Exception{
ResultActions action = mvc.perform(get("/secured").with(user("admin").roles("ADMIN")));
int status = action.andReturn().getResponse().getStatus();
assertTrue("expected status code = 200 ; current status code = " + status, status == 200);
}
What I was not able to achieve until now were things concerning sessions. Most notably I would be interested to verify that session-invalidation is performed correctly.
How can I achieve that?
EDIT:
I was able to find something close to a solution doing the following based on https://stackoverflow.com/a/26281932/6294605 :
@Test
public void logout_shouldInvalidateSession_withLoggedInUser() throws Exception{
ResultActions action = mvc.perform(get("/userAsJSON").with(user("user")));
MockHttpSession session = (MockHttpSession) action.andReturn().getRequest().getSession();
ResultActions action2 = mvc.perform(post("/logout").session(session));
ResultActions action3 = mvc.perform(get("/userAsJSON").session(session));
int status3 = action3.andReturn().getResponse().getStatus();
assertTrue("expected status code = 401 ; current status code = " + status3, status3 == 401);
}
But I am not entirely satisfied with this.
- It requires to process several steps to let me test what I want.
- Resulting from 1.: it is not detached from certain other things to function correctly (e.g. the "/userAsJSON" endpoint returning 401 for not authenticated users).
- Resulting from 2.: it requires additional attention to make sure that test-cases exist that ensure that the formal requirements for my test to be valid are met.
So I would wish for an option to make this less error-prone.
Any ideas?