【问题标题】:PowerMockito to mock a static method inside a class using MockitoJUnitRunnerPowerMockito 使用 MockitoJUnitRunner 在类中模拟静态方法
【发布时间】: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


【解决方案1】:

我认为问题在于您在调用另一个模拟时返回了一个模拟。尝试使用 BeanLocator 的实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多