Mock a static method with mockito

拥有回忆 提交于 2020-07-09 08:04:47

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24655524/mock-a-static-method-with-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!