在Java中使用泛型编写什么单元测试? [英] What unit test to write for a class using generics in Java?

查看:333
本文介绍了在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中使用泛型编写什么单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆