How do I mock a static method that returns void with PowerMock?

前端 未结 4 1282
傲寒
傲寒 2020-12-02 09:41

I have a few static util methods in my project, some of them just pass or throw an exception. There are a lot of examples out there on how to mock a static method that has a

4条回答
  •  生来不讨喜
    2020-12-02 10:11

    You can stub a static void method like this:

    PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());
    

    Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed

    More useful, you can capture the value passed to StaticResource.getResource() like this:

    ArgumentCaptor captor = ArgumentCaptor.forClass(String.class);
    PowerMockito.doNothing().when(
                   StaticResource.class, "getResource", captor.capture());
    

    Then you can evaluate the String that was passed to StaticResource.getResource like this:

    String resourceName = captor.getValue();
    

提交回复
热议问题