Reputation: 2927
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
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.
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.
Upvotes: 11