Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 410
Gábor Csikós Avatar asked Jul 09 '14 13:07

Gábor Csikós


People also ask

Can we mock static method using Mockito?

Since static method belongs to the class, there is no way in Mockito to mock static methods.

How do we mock static methods?

Mocking a No Argument Static Method 0, we can use the Mockito. mockStatic(Class<T> classToMock) method to mock invocations to static method calls. This method returns a MockedStatic object for our type, which is a scoped mock object.

How do you mock a private static method?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.

How do you verify if a static method is called in Mockito?

To define mock behavior and to verify static method invocations, use the MockedStatic reference returned from the Mockito. mockStatic() method. It is necessary to call ScopedMock.


1 Answers

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.

like image 57
pgiecek Avatar answered Sep 28 '22 16:09

pgiecek