Annotation Type WithMockUser


@Documented @Inherited @Retention(RUNTIME) @Target({TYPE,METHOD}) public @interface WithMockUser

Runs a test, or every test of a class, as a signed-in user who exists nowhere but in the test: no user store is asked and no password checked.

@Test
@WithMockUser(username = "ada", roles = "ADMIN")
void anAdminSeesTheReport() throws Exception {
    mvc.perform(get("/admin/report")).andExpect(status().isOk());
}

Every request the test sends through MockMvc is from that user, whatever session or credentials it carries, and SecurityContextHolder.getContext() on the test's own thread names them too. Requests sent over a socket with TestRestTemplate are not affected: they are served on the server's threads and authenticate as a real client does.

On a method it replaces what the class says. The principal is a User.

  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    The user's authorities, as they are written, in place of roles().
    The user's password, for code that reads it.
    The user's roles, each granted as ROLE_ and the name.
    The user's name; user unless set here or in value().
    The user's name; the same as username(), which wins when both are set.
  • Element Details

    • value

      String value
      The user's name; the same as username(), which wins when both are set.
      Default:
      "user"
    • username

      String username
      The user's name; user unless set here or in value().
      Default:
      ""
    • roles

      String[] roles
      The user's roles, each granted as ROLE_ and the name. Ignored when authorities() is given.
      Default:
      {"USER"}
    • authorities

      String[] authorities
      The user's authorities, as they are written, in place of roles().
      Default:
      {}
    • password

      String password
      The user's password, for code that reads it.
      Default:
      "password"