繁体   English   中英

使用 PowerMockito 测试静态方法时出现 MissingMethodInvocationException

[英]MissingMethodInvocationException when using PowerMockito to test static method

我阅读了几篇关于使用 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() 中,您不会在模拟上调用方法,而是在其他对象上调用方法。

你可以试试这个:

@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");
    }

我实际上正在为类似的问题而苦苦挣扎,但我确实看到上述问题。 @RunWith 注释是 JUnit 库的一部分。 AbstractTestNGSpringContextTests 和 @BeforeMethod 是 TestNG 库的一部分。 这可能就是您遇到问题的原因。 除非有人想反驳这个说法,否则我相信这两个单元测试库不能相互配合。 至少不是那样。

@RunWith(PowerMockRunner.class) 将无法像 org.junit.Before 一样选择 @BeforeMethod。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM