2016-08-01 36 views
0

我檢查控制方法,包括用電話:如何在Spring安全中模擬getCurrentLoginId?

SecurityUtils.getCurrentLoginId() 

然而,當我運行這個測試

SecurityContext securityContext = Mockito.mock(SecurityContext.class); 
    Mockito.when(SecurityUtils.getCurrentLoginId()).thenReturn((long) 1); 
    SecurityContextHolder.setContext(securityContext); 

    RequestBuilder requestBuilder = MockMvcRequestBuilders 
      .post(uri) 
      .with(user("admin").password("pass").roles("USER","ADMIN")) 
      .with(csrf()) 
      .param("blogId", "" + blogId) 
      .content(mapToJson(post)) 
      .contentType(MediaType.APPLICATION_JSON) 
      .accept(MediaType.APPLICATION_JSON); 

我得到:

java.lang.IllegalStateException: User not found! 

回答

1

你試圖嘲弄靜態方法,而Mockito不支持此功能。請使用PowerMock代替。

你會發現通過PowerMock here嘲弄靜態方法的一些例子。

+0

我正在嘗試將Mockito應用於powermock,但是當我添加PowerMockRunner.class - 它看起來像我失去了WebApplicaitonContext - 可能是錯誤的? – poseid

+0

問題可能是RunWith丟失了SpringTestRunner上下文 – poseid

+1

你是對的 - 爲了啓用Spring Context,你必須使用Spring Junit Runner運行測試,並且PowerMock需要啓用它自己的runner。爲了解決這個問題,PowerMock提供了@PowerMockRunnerDelegate。 [這裏](https://github.com/jayway/powermock/wiki/JUnit_Delegating_Runner#using-powermock-with-junit-delegation-runner)你會找到解釋和一些例子。 – mxf