Java:从List传递构造函数的参数

时间:2017-07-26 11:53:08

标签: java junit

我有类T,它由类A,B,C扩展。每个类都有不同的字段。我需要通过创建它并运行一些方法来测试每个子类,但是我宁愿使用@Theory@Datapoints而不是每个子类的单独测试。我能这样做吗?

我想到了:

@Datapoints
List<Pair>

其中Pair将链接:

  • Class<? extends T>哪个子类,
  • List<?>获取构造函数所需的参数

但我现在陷入了如何使用@Theory内的给定参数从给定类创建对象的问题。可以吗?有什么建议?

编辑:似乎以上不清楚。这是一个例子:

class Pair<L, R> {
    private L l;
    private R r;
    ...
} 

class T {
    private String field1;

    T(String s) {
        this.field1 = s;
    }  
} 

class A extends T {
    private String field2;

    A(String s1, String s2) {
        super(s1);
        this.field2 = s2;
    } 
}

class B extends T {
    private String field3;
    private String field4;

    A(String s1, String s2, String s3) {
        super(s1);
        this.field3 = s2;
        this.field4 = s3;
    }  
}

@RunWith(Theories.class)
class Test {
    @Datapoints
    public static List<Pair> = Arrays.asList{
        new Pair(A.class, Arrays.asList(field1, field2)), 
        new Pair(B.class, Arrays.asList(field1, field3, field4)) 
    };

    @Theory
    public void test(Pair p) {
        ?? 
    }
} 

1 个答案:

答案 0 :(得分:0)

这是对我有用的要点:

class T {
    private String field1;

    T(String s) {
        this.field1 = s;
    }  
} 

class A extends T {
    private String field2;

    A(String s1, String s2) {
        super(s1);
        this.field2 = s2;
    } 
}

class B extends T {
    private String field3;
    private String field4;

    A(String s1, String s2, String s3) {
        super(s1);
        this.field3 = s2;
        this.field4 = s3;
    }  
}

@RunWith(Theories.class)
class Test {
    // this can probably be array of arrays instead
    @Datapoints
    public static List<List> = Arrays.asList{
        Arrays.asList(Arrays.asList(A.class), 
                      Arrays.asList(String.class, String.class),  
                      Arrays.asList(field1, field2)), 
        Arrays.asList(Arrays.asList(B.class), 
                      Arrays.asList(String.class, String.class, String.class),
                      Arrays.asList(field1, field3, field4)) 
    };

    @Theory
    public void test(List l) {
        Class<?> c = Class.forName(l.get(0).get(0).toString());
        Class[] types = (Class[]) l.get(1).toArray();
        Object[] args = l.get(2).toArray();


        T t = (T) c.getConstructor(types).newInstance(args);

        //do whatever with t
    }
}