Mock a static method with mockito

25,392

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.

Share:
25,392
Gábor Csikós
Author by

Gábor Csikós

Updated on July 10, 2020

Comments

  • Gábor Csikós
    Gábor Csikós almost 4 years

    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?

  • Hayo Baan
    Hayo Baan about 4 years
    Even though this answer is a couple of years old now, it did help me out in a similar situation. Thanks!