Gábor Csikós
Gábor Csikós

Reputation: 2927

Mock a static method with mockito

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?

Upvotes: 6

Views: 27567

Answers (1)

pgiecek
pgiecek

Reputation: 8240

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.

Upvotes: 11

Related Questions