通用DAO类的通用测试类?

时间:2011-08-29 10:27:03

标签: java junit4

我正在尝试测试一些从Generic继承的DAO类,并且想知道是否有办法编写测试我的通用DAO功能的通用测试类,并创建从其继承的其他测试类

我的通用DAO课程:

 public abstract class GenericDAO<T> {
    private final Class<T> entityClass;

    public GenericDAO(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
    //bunch of methods
    //...
}

继承自我的通用

的样本DAO
public class OptionsDAO extends GenericDAO<Options> {

    public OptionsDAO() {
        super(Options.class);
    }
}

我目前在测试中的目标

public class OptionsDAOTest {
    //...
    @Test
    public void testSomeMethod() {
        OptionsDAO odao = new OptionsDAO(); //this is what blocked me from achieving what i'm trying to do (look @next sction)
    odao.callSomeMethod();
    //Asserts and what not...
    }
    //...
}

这是我希望做的事情

public class GenericDAOTest<T> {

    private final Class<T> entityClass;

    public GenericDAOTest(Class<T> entityClass) {
        this.entityClass = entityClass;
    }
    @Test
    public void testSomeMethod() {
        GenericDAO gdao = ???//how can i get an instance based on the T passed to the class?
    odao.callSomeMethod();
    //Asserts and what not...
    }
    //...
}

public class OptionsDAOTest extends GnericDAOTest<Options> {
    public OptionsDAOTest() {
        super(OptionsDAO.class);
    }    
    //how can i call inhrited methods here to test them on an Options java bean
    //and do the same with oter DAO classes i have?
}

1 个答案:

答案 0 :(得分:0)

  

GenericDAO gdao = ??? //如何根据传递给班级的T获得实例?

如果泛型类提供了无参数构造函数,则可以调用entityClass.newInstance()。 请注意,entityClass的类型为Class<T>,因此类型为T