以这个 JpaDao 类的特定示例rel =nofollow noreferrertitle =JPA Implementation Patterns> article :
public abstract class JpaDao < K,E>实现Dao { protected Class< E> entityClass; @PersistenceContext 受保护的EntityManager entityManager; $ b $ public JpaDao(){ ParameterizedType genericSuperclass =(ParameterizedType)getClass()。getGenericSuperclass(); this.entityClass =(Class< E>)genericSuperclass.getActualTypeArguments()[1]; } public void persist(E entity){entityManager.persist(entity); } public void remove(E entity){entityManager.remove(entity); } public E findById(K id){return entityManager.find(entityClass,id); } $ / code>最好为所有现有的实体编写单元测试应用程序( Order , Customer ,Book等),还是可以接受为单个测试编写单元测试实体,正如这个其他问题所暗示的那样?有没有关于单元测试使用泛型的java类的最佳做法?
您可以为实现这个子类的实体编写一个抽象测试类。 $ b例:
public abstract class JpaDaoTest< K,E> ; { abstract protected E getEntity(); 抽象保护JpaDao getDAO(); @Test public void testPersistCreatesEntity() { JpaDao dao = getDAO(); dao.persist(getEntity()); //断言} }假设正确设置了 getEntity()和关系依赖关系,那么类实现应该能够像泛型一样进行测试。
<因此,通过为泛型子类的所有测试用例子类化这个测试类,您可以免费获得测试。Taking the very specific example of the JpaDao class defined in this article:
public abstract class JpaDao<K, E> implements Dao<K, E> { protected Class<E> entityClass; @PersistenceContext protected EntityManager entityManager; public JpaDao() { ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass(); this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1]; } public void persist(E entity) { entityManager.persist(entity); } public void remove(E entity) { entityManager.remove(entity); } public E findById(K id) { return entityManager.find(entityClass, id); } }would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question? Are there any best practice regarding unit testing java classes using generics?
解决方案You could write an abstract test class for entities which subclass this.
Eg:
public abstract class JpaDaoTest<K,E> { abstract protected E getEntity(); abstract protected JpaDao getDAO(); @Test public void testPersistCreatesEntity() { JpaDao dao = getDAO(); dao.persist(getEntity()); // assert } }The contract you generic classes implement should be able to be tested just as genericlly, assuming that getEntity() sets up and relational dependencies correctly.
Therefore, by subclassing this test class for all the test cases for your generic subclasses, you get the tests for free.
更多推荐
在Java中使用泛型编写什么单元测试?
发布评论