简体   繁体   中英

Generic test class for a generic DAO class?

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 OptionsDAO() {
        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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM