6

我目前在 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() 应该被抑制(因此不会抛出异常),并且还需要验证方法 checkString() 是否实际在方法 factorObject() 中被调用。

更新:抑制与以下代码一起正常工作:

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

...但是它为字符串“s”返回NULL。这是为什么?

4

2 回答 2

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);      
    }
}
于 2013-05-09T12:44:08.883 回答
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();
于 2013-05-09T10:30:43.727 回答