Skip to content
Ameen Abozaid
Planned lessonJNR-036-L05

Testing security

  • Lesson 5 of 8
  • Junior
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, SecurityMockMvcRequestPostProcessors can 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

java
@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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.