调用外部服务的模拟静态方法

Mock static method that calls to external service

我有一个 class,它有一个传递请求并调用服务器检索响应的静态方法。 有没有办法模拟它,因为它是单元测试我不想打服务电话。

String jsonResponse = getMeMyMoney(request)

protected static String getMeMyMoney(request)
{
response = executeService(request)
return response
}

我尝试了这个应该绕过该方法的方法,但它仍然成功了。任何人都知道如何做到这一点

doReturn("1").when(TestClass.getMeMyMoney("S"));

您不能使用 Mockito 模拟静态方法,FAQ 中也有说明。

在 Mockito 之上使用 PowerMock

PowerMockito.mockStatic(TestClass.class);
when(TestClass.getMeMyMoney("S")).thenReturn("1");