Annotation Type 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 ElementsModifier and TypeOptional ElementDescriptionString[]The user's authorities, as they are written, in place ofroles().The user's password, for code that reads it.String[]The user's roles, each granted asROLE_and the name.The user's name;userunless set here or invalue().The user's name; the same asusername(), which wins when both are set.
-
Element Details
-
value
-
username
-
roles
String[] rolesThe user's roles, each granted asROLE_and the name. Ignored whenauthorities()is given.- Default:
{"USER"}
-
authorities
-
password
-