在Java中使用泛型编写什么单元测试?

编程入门 行业动态 更新时间:2024-10-23 19:20:23
本文介绍了在Java中使用泛型编写什么单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以这个 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中使用泛型编写什么单元测试?

本文发布于:2023-10-04 11:36:16,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!