Backend API. Server-side code: this runs in a Codename One backend, not in the app on the device.

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

Methods

public abstract String value() default "user"The user’s name; the same as username, which wins when both are set.
public abstract String username() default ""The user’s name; user unless set here or in value.
public abstract String[] roles() default {"USER"}The user’s roles, each granted as ROLE_ and the name.
public abstract String[] authorities() default {}The user’s authorities, as they are written, in place of roles.
public abstract String password() default "password"The user’s password, for code that reads it.

Method details

value

public abstract String value() default "user"
The user’s name; the same as username, which wins when both are set.

username

public abstract String username() default ""
The user’s name; user unless set here or in value.

roles

public abstract String[] roles() default {"USER"}
The user’s roles, each granted as ROLE_ and the name. Ignored when authorities is given.

authorities

public abstract String[] authorities() default {}
The user’s authorities, as they are written, in place of roles.

password

public abstract String password() default "password"
The user’s password, for code that reads it.