要测试的类:
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());
}