Annotation Interface WithMockAuthentication
@Target({METHOD,TYPE})
@Retention(RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory=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
}
- Author:
- Jérôme Wacongne <ch4mp@c4-soft.com>
-
Nested Class Summary
Nested Classes -
Optional Element Summary
Optional ElementsModifier and TypeOptional ElementDescriptionString[]Class<? extends org.springframework.security.core.Authentication>org.springframework.security.test.context.support.TestExecutionEventDetermines when theSecurityContextis setup.Class<? extends org.springframework.security.core.Authentication>
-
Element Details
-
value
- Default:
- org.springframework.security.core.Authentication.class
-
authType
- Default:
- org.springframework.security.core.Authentication.class
-
name
String name- Default:
- "user"
-
authorities
String[] authorities- Default:
- {"ROLE_USER"}
-
setupBefore
@AliasFor(annotation=org.springframework.security.test.context.support.WithSecurityContext.class) org.springframework.security.test.context.support.TestExecutionEvent setupBeforeDetermines when theSecurityContextis setup. The default is beforeTestExecutionEvent.TEST_METHODwhich occurs duringTestExecutionListener.beforeTestMethod(TestContext)- Returns:
- the
TestExecutionEventto initialize before
- Default:
- TEST_METHOD
-