开发者

Generic test class for a generic DAO class?

开发者 https://www.devze.com 2023-04-01 00:08 出处:网络
I\'m trying to test some DAO Classes that inherit from a Generic one, and was wondering if there was a way to write a generic test class that tests the functionality of my generic DAO, and create othe

I'm trying to test some DAO Classes that inherit from a Generic one, and was wondering if there was a way to write a generic test class that tests the functionality of my generic DAO, and create other test classes inheriting from it

My Generic DAO Class :

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

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

a sample DAO inheriting from my generic one

public class OptionsDAO extends GenericDAO<Options> {

    public Options开发者_运维知识库DAO() {
        super(Options.class);
    }
}

what i have currently in tests

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...
    }
    //...
}

THIS is what I'm hoping to do

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?
}


GenericDAO gdao = ???//how can i get an instance based on the T passed to the class?

You can just call entityClass.newInstance() if the generic class provides a no-arg constructor. Note that entityClass is of type Class<T> and thus of type T.

0

精彩评论

暂无评论...
验证码 换一张
取 消