模拟静态 Liferay 方法

Mocking static Liferay method

我正在尝试像这样模拟 PortalUtil.getPortal() 方法

PowerMock.mockStatic(PortalUtil.class);
Portal mockPortal = Mockito.mock(Portal.class);
Mockito.when(PortalUtil.getPortal()).thenReturn(mockPortal);

我收到以下错误

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
It is a limitation of the mock engine.

我知道 Mockito 不能模拟静态方法,但我也在使用 PowerMock,它应该可以实现这一点。我也尝试使用 PowerMockito.mockStatic() 而不是 PowerMock.mockStatic()

我在 class 级别有以下注释

@RunWith(PowerMockRunner.class)
@PrepareForTest(PortalUtil.class)

我错过了什么?

使用这段代码后,我不再收到 NPE

Portal mockPortal = Mockito.mock(Portal.class);
new PortalUtil().setPortal(mockPortal);