如何抑制和验证私有静态方法调用?

时间:2013-05-09 09:52:32

标签: java junit powermock verify suppress

我目前在JUnit测试中遇到困难,需要一些帮助。所以我用静态方法得到了这个类,它将重构一些对象。为简化起见,我举了一个小例子。这是我的工厂类:

class Factory {

    public static 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 {

        mockStatic(Factory.class);
        suppress(method(Factory.class, "checkString"));
        String s = Factory.factorObject();
        assertEquals("Hello Mary Lou", s);
    }
}

基本上我试图实现的是私有方法checkString()应该被抑制(因此不抛出Exception),还需要验证方法checkString()实际上是在方法factorObject()中调用的。

已更新: 使用以下代码可以正常进行抑制:

suppress(method(Factory.class, "checkString", String.class));
String s = Factory.factorObject();

...然而它为String“s”返回NULL。那是为什么?

2 个答案:

答案 0 :(得分:10)

好的,我终于找到了所有问题的解决方案。如果有人遇到类似问题,请输入以下代码:

import junit.framework.TestCase;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.times;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;

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

    public void testFactory() throws Exception {

        mockStatic(Factory.class, Mockito.CALLS_REAL_METHODS);
        suppress(method(Factory.class, "checkString", String.class));
        String s = Factory.factorObject();
        verifyPrivate(Factory.class, times(1)).invoke("checkString", anyString()); 
        assertEquals("Hello Mary Lou", s);      
    }
}

答案 1 :(得分:4)

哟可以这样做:

PowerMockito.doNothing().when(Factory.class,"checkString");

有关详细信息,请访问:
http://powermock.googlecode.com/svn/docs/powermock-1.3.7/apidocs/org/powermock/api/mockito/PowerMockito.html

编辑:

ClassToTest spy = spy(new ClassToTest ());
doNothing().when(spy).methodToSkip();
spy.methodToTest();