Testing security
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
write tests for secured endpoints.
Planned topics
- Add the Spring Security test dependency.
@WithMockUser(roles = "ADMIN")runs a test as a fake user.- With MockMvc,
SecurityMockMvcRequestPostProcessorscan set a user or a JWT per request. - Always test three cases: anonymous, wrong role, right role.
- A test of "anonymous gets 401" would have caught a forgotten
permitAll.
Draft outline details
Demonstration
@Test @WithMockUser(roles = "CUSTOMER")
void customerCannotCreateProduct() throws Exception {
mvc.perform(post("/api/products").contentType(APPLICATION_JSON).content("{}"))
.andExpect(status().isForbidden());
}Check your understanding
Which three callers should every endpoint be tested with?
Show answer
Anonymous, a user without the role, a user with the role.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.