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 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
    Modifier and Type
    Class
    Description
    static final class 
     
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
     
    Class<? extends org.springframework.security.core.Authentication>
     
     
     
    org.springframework.security.test.context.support.TestExecutionEvent
    Determines when the SecurityContext is setup.
    Class<? extends org.springframework.security.core.Authentication>
     
  • Element Details

    • value

      @AliasFor("authType") Class<? extends org.springframework.security.core.Authentication> value
      Default:
      org.springframework.security.core.Authentication.class
    • authType

      @AliasFor("value") Class<? extends org.springframework.security.core.Authentication> authType
      Default:
      org.springframework.security.core.Authentication.class
    • principalType

      Class<?> principalType
      Default:
      java.lang.String.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 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