次のロジックで 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>
互換性があります..しかし、それでも応答は正しくありません。