3

亲爱的 stackoverflow 同志,我在让特定的 PowerMock / Mockito 案例工作时再次遇到问题。问题是,我需要验证私有静态方法的调用,该方法是从公共非静态方法调用的。我之前发布的一个类似示例如何抑制和验证私有静态方法调用?

这是我的代码:

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 次。但是无论我在 times() 中输入什么值,它总是会验证它是真的...... halp :(

4

1 回答 1

13

好的,我想我找到了答案,但很头疼。Rudy 给了我使用间谍的最后提示,但它仍然不是微不足道的(尽管解决方案看起来“很容易”)。这是完整的解决方案:

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()); 
    }
}
于 2013-05-13T07:32:39.840 回答