使用PowerMockito测试静态方法时缺少MissingMethodInvocationException

时间:2019-01-09 16:46:51

标签: java junit powermockito

我读了几篇关于使用powermockito而不是仅仅用Mockito测试静态方法的文章,但是切换到Power Mockito之后,我仍然遇到相同的错误。以下是我的课程和例外。两种情况都不能解释我的错误。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToBeMocked.class})
public class Test extends AbstractTestNGSpringContextTests {
    @Mock
    Object1 o1;

    @BeforeMethod
    public void init() {
        mockStatic(ClassToBeMocked.class);

        PowerMockito.when(ClassToBeMocked.getMethod()).thenReturn("string");
    }

最后一行代码导致此异常 org.mockito.exceptions.misusing.MissingMethodInvocationException: when()需要一个参数,该参数必须是“模拟的方法调用”。 例如:     when(mock.getArticles())。thenReturn(articles);

此外,由于以下原因,可能会出现此错误: 1.存根:final / private / equals()/ hashCode()方法之一。    那些方法 无法存根/验证。    不支持在非公共父类上声明的模拟方法。 2.在when()内部,您不会在模拟对象上调用方法,而是在其他某个对象上调用。

2 个答案:

答案 0 :(得分:0)

您能尝试一下吗?

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassToBeMocked.class})
public class Test extends PowerMockTestCase {
    @Mock
    Object1 o1;

    @ObjectFactory
    public IObjectFactory getObjectFactory() {
        return new org.powermock.modules.testng.PowerMockObjectFactory();
    }

    @BeforeMethod
    public void init() {
        mockStatic(ClassToBeMocked.class);

        PowerMockito.when(ClassToBeMocked.getMethod()).thenReturn("string");
    }

答案 1 :(得分:0)

我实际上正在努力解决类似的问题,但是我确实发现上述内容有问题。 @RunWith批注是JUnit库的一部分。 AbstractTestNGSpringContextTests和@BeforeMethod是TestNG库的一部分。这可能就是您遇到问题的原因。除非有人希望与该声明相抵触,否则我相信这两个单元测试库不能相互配合。至少不是那样。

@RunWith(PowerMockRunner.class)无法像使用org.junit.Before一样拾取@BeforeMethod。