簡體   English   中英

如何在靜態方法上使用 Mockito.verify()?

[英]How to use Mockito.verify() on static methods?

我正在研究 Junit 和 Mockito。 在我的項目中,我有一個 SocialDataAccess 控制器,其代碼如下所示:

public class SocialDataAccessController implements Controller{

private SocialAuthServiceProvider socialAuthServiceProvider;

@Override
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String provider = request.getParameter("pId");
        String appCode =  request.getParameter("apc");

         * check if data in session is of the same provider orof different
         * provider, if different then remove auth and request token
         **/

        SocialUtility.removeOtherProviderAuthTokenFromSession(request,provider);

        try {
            /** creating the OAuthService object based on provider type **/
            OAuthService service = getSocialAuthServiceProvider().getOAuthServiceProvider(appCode, provider);
            .....
            ........
            ............            
return new ModelAndView("redirect:callback.html?pId=" + provider);
    }

public SocialAuthServiceProvider getSocialAuthServiceProvider() {
        return socialAuthServiceProvider;
    }

}

這就是我所做的。 我提出了一個請求,我的請求成功地調用了我的控制器。 當我嘗試使用Mockito.verify()來測試我的靜態方法是否被調用時,我收到如下所示的錯誤。

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(
        locations={
            "file:/opt/div/BatchWorkspace/harvest_branch/WebContent/WEB-INF/test-servlet.xml"
        }
)

public class TestSocialDataAccessController {   
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();      
    }


    @SuppressWarnings("static-access")
    @Test
    public void testBasicSetUp() throws Exception{
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/social-connect.html")
                .param("apc","tj")
                .param("src","google")
                .param("pId","ggl")
                .param("cl","xxxxxxxxxxxxxx");

        mockMvc.perform(requestBuilder)
       .andDo(MockMvcResultHandlers.print())
       .andExpect(MockMvcResultMatchers.status().isMovedTemporarily())
       .andExpect(MockMvcResultMatchers.redirectedUrl("xxxxxxxx"));

           SocialUtility sutil = new SocialUtility();
           SocialUtility spy = Mockito.spy(sutil);
           MockHttpServletRequest request = requestBuilder.buildRequest(wac.getServletContext());
           Mockito.verify(spy).removeOtherProviderAuthTokenFromSession(request,Matchers.anyString());          

    }
}

我得到的錯誤:

org.mockito.exceptions.misusing.UnfinishedVerificationException: 
Missing method call for verify(mock) here:
-> at com.tj.harvest.testcase.TestSocialDataAccessController.testBasicSetUp(TestSocialDataAccessController.java:88)

Example of correct verification:
    verify(mock).doSomething()

Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.

    at com.tj.harvest.testcase.TestSocialDataAccessController.testBasicSetUp(TestSocialDataAccessController.java:89)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597).

我的問題是:

  1. 我可以在方法removeOtherProviderAuthTokenFromSession(request,provider)上使用Mockito.verify()嗎? 如果“是”如何? &如果“否”為什么? SocialUtility是類名,方法是靜態的。 請求與到達控制器的請求相同。 provider 是一個字符串。 我不想使用 PowerMockito。

  2. 我還想在getOAuthServiceProvider(appCode, provider)上使用驗證。 我怎樣才能做到這一點?

任何幫助將不勝感激。

使用 Mockito -> MockedStatic 驗證靜態方法。

如果該方法有參數並且你想驗證它那么它將通過這種方式進行驗證:

@Test
void testMethod() {
  try (MockedStatic<StaticProperties> theMock = Mockito.mockStatic(StaticProperties.class)) {
    theMock.when(StaticProperties.getProperty("abc", "xyz", "lmn"))).thenReturn("OK");

    //code .....

    theMock.verify(() -> StaticProperties.getProperty("abc", "xyz", "lmn"));
  }
  
}
  1. 您必須為此 Mockito 使用 PowerMockito 單獨將無法驗證這一點

    PowerMockito.doNothing().when(SocialUtility.class, "removeOtherProviderAuthTokenFromSession", any(MockHttpServletRequest.class), anyString());
  2. 您可以模擬您的getSocialAuthServiceProvider()或在調用SocialDataAccessController時監視它

關於你的第二個問題:

我還想在 getOAuthServiceProvider(appCode, provider) 上使用驗證。 我怎樣才能做到這一點?

答案可能是這樣的:

Mockito.verify(this.getSocialAuthServiceProvider())
       .getOAuthServiceProvider(Mockito.isA(String.class), Mockito.isA(String.class));

如果我遺漏了什么,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM