@Target(value={METHOD,TYPE}) @Retention(value=RUNTIME) @Inherited @Documented @WithSecurityContext(factory=WithMockAuthentication.Factory.class) public @interface WithMockAuthentication
Populates SecurityContext with an Authentication Mock.
@Test
@WithMockAuthentication
public demoDefaultUserNameAndAuthorities {
// test as "user" granted with "ROLE_USER"
}
@Test
@WithMockAuthentication(name = "Ch4mpy", authorities = { "ROLE_TESTER", "ROLE_AUTHOR" })
public demoCustomUserNameAndAuthorities {
// test as "Ch4mpy" granted with "ROLE_TESTER", "ROLE_AUTHOR"
}
@Test
@WithMockAuthentication(JwtAuthenticationToken.class)
public demoCustomAuthenticationImpl {
final var jwt = mock(Jwt.class);
when(jwt.getSubject()).thenReturn(auth.getName());
final var auth = (JwtAuthenticationToken) SecurityContextHolder.getContext();
when(auth.getPrincipal()).thenReturn(jwt);
// test as "user" granted with "ROLE_USER", the Authentication in the SecurityContext being a JwtAuthenticationToken mock
}
| Modifier and Type | Optional Element and Description |
|---|---|
String[] |
authorities |
Class<? extends org.springframework.security.core.Authentication> |
authType |
String |
name |
org.springframework.security.test.context.support.TestExecutionEvent |
setupBefore
Determines when the
SecurityContext is setup. |
Class<? extends org.springframework.security.core.Authentication> |
value |
@AliasFor(value="authType") public abstract Class<? extends org.springframework.security.core.Authentication> value
@AliasFor(value="value") public abstract Class<? extends org.springframework.security.core.Authentication> authType
public abstract String name
public abstract String[] authorities
@AliasFor(annotation=org.springframework.security.test.context.support.WithSecurityContext.class) public abstract org.springframework.security.test.context.support.TestExecutionEvent setupBefore
SecurityContext is setup. The default is before
TestExecutionEvent.TEST_METHOD which occurs during
TestExecutionListener.beforeTestMethod(TestContext)TestExecutionEvent to initialize beforeCopyright © 2022. All rights reserved.