软件测试 —— 如何测试私有构造函数(反射机制)

要测试的类:

public class Argument {

    private final Value value;
    private final Variable variable;
    private final boolean isValue;

    private Argument(Value value, Variable variable, boolean isValue) {
        this.value = value;
        this.variable = variable;
        this.isValue = isValue;
    }

    public static Argument value(Value value) {
        return new Argument(value, null, true);
    }

    public static Argument variable(Variable variable) {
        return new Argument(null, variable, false);
    }

    public boolean isValue() {
        return this.isValue;
    }

    public boolean isVariable() {
        return !this.isValue;
    }

    public Value getValue() {
        return this.value;
    }

    public Variable getVariable() {
        return this.variable;
    }

    public String toString() {
        if (isValue)
            return value.toString();
        return variable.toString();
    }

}

测试用例(仅写一个测试)

  @Test
    public void testIsValue() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Value v1 = new Value("Test01");
        Variable v2 = new Variable("Test02");
        
        Class clazz = Argument.class;
        //调用带参的、私有构造函数
        Constructor c1 = clazz.getDeclaredConstructor(new Class[]{Value.class, Variable.class, boolean.class});
        c1.setAccessible(true);    
        Argument t = (Argument) c1.newInstance(new Object[]{v1, v2, true});
t.value(v1); assertEquals(
true, t.isValue()); t.variable(v2); assertEquals(true, t.isValue()); }

 

posted @ 2017-09-22 21:11  douzujun  阅读(681)  评论(0编辑  收藏  举报