【发布时间】:2021-11-18 14:48:15
【问题描述】:
我想在具有@RunWith(MockitoJUnitRunner.class) 的测试类中使用 PowerMockito。我做了以下静态方法模拟:
BeanLocator mockBeanLocator = mock(BeanLocator.class);
PowerMockito.mockStatic(PortalBeanLocatorUtil.class);
PowerMockito.when(PortalBeanLocatorUtil.getBeanLocator()).thenReturn(mockBeanLocator);
最后一行不起作用。我收到此错误消息:
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 do not 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.
PortalBeanLocatorUtil是一个带有public static BeanLocator getBeanLocator()的公共类。所有这些类都来自第三方库。模拟getBeanLocator()static 方法的正确方法是什么?
【问题讨论】:
-
修复你的课程并注入
BeanLocator。 -
@chrylis-cautiouslyoptimistic- 我不确定我是否听从你的建议。你指的是哪个班级?我无法修改 BeanLocator 和 PortalBeanLocatorUtil
-
相反,尝试使用
BDDMockito进行存根:BDDMockito.given(PortalBeanLocatorUtil.getBeanLocator()).willReturn(mockBeanLocator);
标签: java static mockito powermockito