Mockito3.8 如何mock静态方法 (如何mock PageHelper)

目中遇到需要mock PageHelper,因为用到了startPage方法,而此方法是静态方法,如果需要mock静态方法,网上说法比较多的都是需要用Powermock,而这就需要引入新的依赖,这样的话就比较臃肿了,那如何不引入新依赖,百搜不得其解,那如何解决这个问题呢?经过排查思考,如下。

升级org.mockito版本至3.8.0(3.4.0之前的版本不支持mock静态方法)
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
然后你就兴高采烈的去mock PageHelper了,如下面这样
Page<Plan> planPage = new Page<>();
MockedStatic<PageHelper> pageMethodMock = mockStatic(PageHelper.class);
pageMethodMock.when(()->PageHelper.startPage(anyInt(),anyInt())).thenReturn(planPage);
你就会发现会抱这样的错
rg.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:

-> at so.dian.leto.service.PlanServiceTest.lambda$paging$0(PlanServiceTest.java:143)
-> at so.dian.leto.service.PlanServiceTest.lambda$paging$0(PlanServiceTest.java:143)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use

而正确做法应该是这样

MockedStatic<PageMethod> pageMethodMock = mockStatic(PageMethod.class);
pageMethodMock.when(()->PageHelper.startPage(anyInt(),anyInt())).thenReturn(planPage);
或者这样

MockedStatic<PageMethod> pageMethodMock = mockStatic(PageMethod.class);
pageMethodMock.when(()->PageMethod.startPage(anyInt(),anyInt())).thenReturn(planPage);
我们点开startPage方法,会发现这个方法是父类PageMethod的方法,PageHelper是继承而 来,所以我们必须要去Mock父类。

用完之后记得pageMethodMock.close()否则会出现这个错误

For com.github.pagehelper.page.PageMethod, static mocking is already registered in the current thread ,To create a new mock, the existing static mock registration must be deregistered

这是因为测试用例中多次mock了PageMethod

posted on 2022-06-10 18:45  1450811640  阅读(2241)  评论(0编辑  收藏  举报