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?
Since static method belongs to the class, there is no way in Mockito to 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.
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.
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.
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.
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
Mock security context
SecurityContext context = mock(SecurityContext.class);
Ensure your mock returns the respective authentication
when(context.getAuthentication()).thenReturn(auth);
Set security context into holder
SecurityContextHolder.setContext(securityContext);
Now every call to SecurityContextHolder.getContext().getAuthentication()
should return authentication object created in step 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With