[使用PowerMockito测试静态方法时,MissingMethodInvocationException

问题描述 投票:0回答:2

我读了几篇有关使用powermockito而不是仅仅用嘲讽来测试静态方法的文章,但是在切换到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()内部,您不会在模拟对象上调用方法,而是在其他某个对象上调用。

java junit powermockito
2个回答
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"); }


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

@ RunWith(PowerMockRunner.class)将无法像使用org.junit.Before那样拾取@BeforeMethod。另外,AbstractTestNGSpringContextTests不能与@Mock一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.