Mocking static Liferay method

柔情痞子 提交于 2019-12-12 04:56:51

问题


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?


回答1:


After using this bit of code I stopped getting NPE

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


来源:https://stackoverflow.com/questions/28500954/mocking-static-liferay-method

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