简体   繁体   中英

Mocking static Liferay method

I'm trying to mock the PortalUtil.getPortal() method like so

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

I'm getting the below error

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.

I know Mockito cannot mock static methods but I'm also using PowerMock which is supposed to make this possible. I also tried using PowerMockito.mockStatic() instead of PowerMock.mockStatic()

I have the below annotations at class level

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

What am I missing?

After using this bit of code I stopped getting NPE

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM