Gáb*_*kós 5 java unit-testing mocking mockito
我想在 Mockito 中模拟一个静态方法。
据我所知这是不可能的,我该如何解决这个问题?powermock 不是一个选项。
我希望我的身份验证变量不会为空。
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Run Code Online (Sandbox Code Playgroud)
pgi*_*cek 10
正如您所指出的,使用 Mockito 模拟静态方法是不可能的,并且由于您不想使用 Powermock 或其他工具,您可以在测试中尝试以下操作。
创建测试认证对象
Authentication auth = new ... // create instance based on your needs and with required attributes or just mock it if you do not care
模拟安全上下文
SecurityContext context = mock(SecurityContext.class);
确保您的模拟返回相应的身份验证
when(context.getAuthentication()).thenReturn(auth);
将安全上下文设置为持有者
SecurityContextHolder.setContext(securityContext);
现在每次调用都SecurityContextHolder.getContext().getAuthentication()应该返回在步骤 1 中创建的身份验证对象。