简体   繁体   English

如何在静态方法上使用 Mockito.verify()?

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

I am working on Junit & Mockito.我正在研究 Junit 和 Mockito。 In my project I have a SocialDataAccess Controller whose code goes like this:在我的项目中,我有一个 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;
    }

}

This is what I have done.这就是我所做的。 I have made a request and my request successfully calls my controller.我提出了一个请求,我的请求成功地调用了我的控制器。 When I try to use Mockito.verify() to test whether my static method is called or not, I get an error as shown below.当我尝试使用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());          

    }
}

The error which I got:我得到的错误:

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).

My questions are:我的问题是:

  1. Can I use Mockito.verify() on my method removeOtherProviderAuthTokenFromSession(request,provider) .我可以在方法removeOtherProviderAuthTokenFromSession(request,provider)上使用Mockito.verify()吗? If "yes" How?如果“是”如何? & If "NO" why? &如果“否”为什么? SocialUtility is the name of class and the method is static. SocialUtility是类名,方法是静态的。 Request is the same request which comes to the controller.请求与到达控制器的请求相同。 And provider is a string. provider 是一个字符串。 I don't want to use PowerMockito.我不想使用 PowerMockito。

  2. I also want to use verify on getOAuthServiceProvider(appCode, provider) .我还想在getOAuthServiceProvider(appCode, provider)上使用验证。 How can I do this?我怎样才能做到这一点?

Any Help would be appreciable.任何帮助将不胜感激。

To verify a static method using Mockito -> MockedStatic.使用 Mockito -> MockedStatic 验证静态方法。

If the method has parameters and you want to verify it then it will be verify by this way:如果该方法有参数并且你想验证它那么它将通过这种方式进行验证:

@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. You have to use PowerMockito for this Mockito alone wont be able to verify this您必须为此 Mockito 使用 PowerMockito 单独将无法验证这一点

    PowerMockito.doNothing().when(SocialUtility.class, "removeOtherProviderAuthTokenFromSession", any(MockHttpServletRequest.class), anyString());
  2. You can mock your getSocialAuthServiceProvider() or spy it when you call your SocialDataAccessController您可以模拟您的getSocialAuthServiceProvider()或在调用SocialDataAccessController时监视它

Regarding your 2nd question:关于你的第二个问题:

I also want to use verify on getOAuthServiceProvider(appCode, provider).我还想在 getOAuthServiceProvider(appCode, provider) 上使用验证。 How can I do this?我怎样才能做到这一点?

Answer may be like this:答案可能是这样的:

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

Let me know if I'm missing something.如果我遗漏了什么,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM