Powermock验证非静态方法中的私有静态方法调用

时间:2013-05-13 06:12:45

标签: java mockito powermock non-static

亲爱的stackoverflow同志, 我再次遇到一个问题,让特定的PowerMock / Mockito案例起作用。 问题是,我需要验证私有静态方法的调用,该方法是从公共非静态方法调用的。我之前在How to suppress and verify private static method calls?

上发布的类似示例

这是我的代码:

class Factory {

        public String factorObject() throws Exception {
            String s = "Hello Mary Lou";
            checkString(s);
            return s;
        }

        private static void checkString(String s) throws Exception {
            throw new Exception();
        }
    }

这是我的测试类:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {

    public void testFactory() throws Exception {

        Factory factory = mock(Factory.class);
        suppress(method(Factory.class, "checkString", String.class));
        String s = factory.factorObject();
        verifyPrivate(factory, times(8000)).invoke("checkString", anyString());
    }
}

这里的问题是,测试成功,但不应该。它不应该是因为私有静态方法应该被正确调用1次。但无论我在时间()中放入什么价值,它总是将其验证为真......停止:(

1 个答案:

答案 0 :(得分:11)

好的,我想我找到了答案,但这很头疼。鲁迪给了我最后的暗示使用间谍,但它仍然不是微不足道的(虽然解决方案看起来像#34;宝贝容易")。这是完整的解决方案:

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.spy;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {

    public void testFactory() throws Exception {

        Factory factorySpy = spy(new Factory());
        String s = factorySpy.factorObject();
        doNothing().when(factorySpy, "checkString", anyString());
        verifyPrivate(factorySpy, times(1)).invoke("checkString", anyString()); 
    }
}