PowerMock Mockito: how to mock all static methods?

隐身守侯 提交于 2019-12-04 03:40:55

问题


Do we need to mock all static methods of a class when using PowerMock (with Mockito)? I mean, suppose we have:

class MockMe {
   public static MockMe getInstance(){
              //return new Instance via complex process;
   }

   public static List<X> anotherStaticMethod(){
      // does xyz
   }
}

My question, if I need to mock getInstance method, is it necessary to mock "anotherStaticMethod" as well?

PowerMock version:1.3, Mockito version:1.8


回答1:


No you can use partial mocking using spy in PowerMockito. Or you can use the stubbing API:

stub(method(MockMe.class, "getInstance")).toReturn(myMockMeInstance);



回答2:


Mocking Static Method How to mock and stub:

Add @PrepareForTest at class level.

@PrepareForTest(Static.class) // Static.class contains static methods

Call PowerMockito.mockStatic() to mock a static class (use PowerMockito.spy(class) to mock a specific method):

PowerMockito.mockStatic(Static.class);

Just use Mockito.when() to setup your expectation:

Mockito.when(Static.firstStaticMethod(param)).thenReturn(value);


来源:https://stackoverflow.com/questions/4851573/powermock-mockito-how-to-mock-all-static-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!