有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我目前在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。为什么


共 (1) 个答案