PowerMock静态类不会模拟

时间:2012-09-14 08:04:41

标签: mocking testng static-methods mockito

public class TestStatic {
    public static int methodstatic(){
        return 3;
    }
}


@Test
@PrepareForTest({TestStatic.class})
public class TestStaticTest extends PowerMockTestCase {

    public void testMethodstatic() throws Exception {
        PowerMockito.mock(TestStatic.class);
        Mockito.when(TestStatic.methodstatic()).thenReturn(5);
        PowerMockito.verifyStatic();
        assertThat("dff",TestStatic.methodstatic()==5);
    }

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

例外:

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 don't call method on mock but on some other object.

我通过Intellij运行它,遗留代码有很多方法......

有人有想法,我经历了官方的tuto,没有办法让这个简单的测试工作

2 个答案:

答案 0 :(得分:2)

我看了一下我对旧版代码的测试,我看到你打电话给PowerMockito.mock(TestStatic.class)而不是PowerMockito.mockStatic(TestStatic.class)。如果您使用PowerMockito.when(...)Mockito.when(...)无关紧要,因为第一个只是委托给第二个。

还有一句话:我明白,也许您必须测试遗留代码。也许你可以用JUnit4风格做到这一点,只是为了不产生遗留测试? Brice提到的例子很好。

答案 1 :(得分:0)

看看这个答案:Mocking Logger and LoggerFactory with PowerMock and Mockito

如果你想要静态调用Mockito.when,你也不应该使用PowerMockito.when

Statics是一个可测试性的噩梦,你尽可能地避免这种情况,并重新设计你的设计,以便不再使用静态或不必使用PowerMock技巧来测试你的生产代码。

希望有所帮助。

干杯, 布莱斯