5

I want to mock a static method in Mockito.

As far as I know this is not possible, how can I get around the problem? powermock is not an option.

I want that my authentication variable won't be null.

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

I read an answer here but I don't know how to put this answer to code. Can someone give a solution?

Community
  • 1
  • 1
Gábor Csikós
  • 2,787
  • 7
  • 31
  • 57
  • 1
    Inject the SecurityContext instead of looking it up using SecurityContextHolder.getContext(). If you posted more code, we could me more helpful. – JB Nizet Jul 09 '14 at 13:59

1 Answers1

10

As you pointed out, it is not possible to mock static methods with Mockito and since you do not wanna use Powermock or other tools, you can try something as follows in your tests.

  1. Create test authentication object

    Authentication auth = new ... // create instance based on your needs and with required attributes or just mock it if you do not care

  2. Mock security context

    SecurityContext context = mock(SecurityContext.class);

  3. Ensure your mock returns the respective authentication

    when(context.getAuthentication()).thenReturn(auth);

  4. Set security context into holder

    SecurityContextHolder.setContext(securityContext);

Now every call to SecurityContextHolder.getContext().getAuthentication() should return authentication object created in step 1.

Community
  • 1
  • 1
pgiecek
  • 7,970
  • 4
  • 39
  • 47
  • Even though this answer is a couple of years old now, it did help me out in a similar situation. Thanks! – Hayo Baan May 08 '20 at 16:56