PowerMock for SecurityContextHolder无法正常工作

时间:2015-09-29 05:05:21

标签: spring spring-security mockito powermockito

以下逻辑从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 Dependencies确保

<!-- 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>

兼容..但响应仍然不正确。

1 个答案:

答案 0 :(得分:0)

我看到了您的代码,感觉mockStatic SecurityContextHolder.class中有一些内容。

编辑:我也看到你使用PrepareForTest(YourTestClass),但我不明白你为什么会这样做。 @PrepareForTest语句仅用于类(而不是对象!),因此您需要在实例化之前更改它们。例如。当您更改该类的所有实例的某些代码的行为时,您希望PrepareForTest SecurityContextHolder.class类(例如静态...)

你可以试试这个:

@RunWith(PowerMockRunner.class)
@PrepareForTest(SecurityContextHolder.class)
public testClass{         
    @Test
    public void testSomething(){
        // this prepares the class; all static methods get a default return value (in this case type Object is returned and the default returned object is null)
        PowerMockito.mockStatic(SecurityContextHolder.class, new Answer<Object>() 
        {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                return null;
            }
        });

        //Now the class is prepared, we can just change the behaviour of the static method in the way we would like.
        String in = "example input string";
        String out = "example output string";        

        PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(out);
    }
    //..body
}