Annotation Interface WithMockAuthentication


@Target({METHOD,TYPE}) @Retention(RUNTIME) @Inherited @Documented @WithSecurityContext(factory=Factory.class) public @interface WithMockAuthentication

Populates SecurityContext with an Authentication Mock.

Sample usage:
 @Test
 @WithMockAuthentication
 public demoDefaultUserNameAndAuthorities {
   // test as "user" granted without any authority
 }

 @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 without any authority, the Authentication in the SecurityContext being a JwtAuthenticationToken mock
 }
 
Author:
Jérôme Wacongne <ch4mp@c4-soft.com>
  • Element Details

    • authorities

      @AliasFor("value") String[] authorities
      Default:
      {}
    • value

      @AliasFor("authorities") String[] value
      Default:
      {}
    • authType

      Class<? extends org.springframework.security.core.Authentication> authType
      Default:
      org.springframework.security.core.Authentication.class
    • principalType

      Class<?> principalType
      Default:
      java.security.Principal.class
    • name

      String name
      Default:
      "user"
    • setupBefore

      @AliasFor(annotation=org.springframework.security.test.context.support.WithSecurityContext.class) org.springframework.security.test.context.support.TestExecutionEvent setupBefore
      Determines when the SecurityContext is setup. The default is before TestExecutionEvent.TEST_METHOD which occurs during TestExecutionListener.beforeTestMethod(TestContext)
      Returns:
      the TestExecutionEvent to initialize before
      Default:
      TEST_METHOD