对于以下从 SecurityContextHolder 中检索名称的逻辑,无法找到完成模拟测试的解决方案。
String userName = SecurityContextHolder.getContext()
.getAuthentication().getName();
模拟测试 :
@RunWith(PowerMockRunner.class)
@PrepareForTest(CustomAuthenticationSuccessHandlerTest.class)
public class CustomAuthenticationSuccessHandlerTest {
private CustomAuthenticationSuccessHandler successHandler;
@Before
public void setUp() {
successHandler = new CustomAuthenticationSuccessHandler();
}
// https://github.com/pkainulainen/spring-mvc-test-examples/blob/master/security-url-based/src/test/java/net/petrikainulainen/spring/testmvc/security/util/SecurityContextUtilTest.java
@Test
public void test() {
HttpServletRequest mockRequest = PowerMockito.mock(HttpServletRequest.class);
HttpServletResponse mockResponse = PowerMockito.mock(HttpServletResponse.class);
PowerMockito.mockStatic(SecurityContextHolder.class);
SecurityContext mockSecurityContext = PowerMockito.mock(SecurityContext.class);
Authentication authenticationMock = PowerMockito.mock(Authentication.class);
PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext);
PowerMockito.when(mockSecurityContext.getAuthentication()).thenReturn(authenticationMock);
PowerMockito.when(authenticationMock.getName()).thenReturn("userName");
...
Maven 依赖项确保
<!-- Mock Objects Library for Java -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
和
<powermock.version>1.6.2</powermock.version>
兼容..但响应仍然不正确。