模拟静态Liferay方法 [英] Mocking static Liferay method

查看:157
本文介绍了模拟静态Liferay方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

我收到以下错误

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()

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()

我在课堂上有以下注释

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

我想念什么?

推荐答案

使用了这段代码后,我停止获取NPE

After using this bit of code I stopped getting NPE

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

这篇关于模拟静态Liferay方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆