测试使用 JPA 实现的 DAO 类

发布于 2024-11-06 00:50:19 字数 4529 浏览 0 评论 0原文

我在 Java EE Web 项目中实现的 DAO 类之一位于下面

@Repository("ClientsimpleDAO")
public class ClientsimpleDAOImp implements ClientsimpleDAO {
    private static final Log log = LogFactory.getLog(ClientsimpleDAOImp.class);
    @PersistenceContext
    EntityManager em;
    @Override
    public void delete(Clientsimple clientsimple) {
        // TODO Auto-generated method stub
        log.debug("removing clientsimple");
        try{
            em.remove(clientsimple);
            log.debug("clientsimple removed");
        }
        catch(RuntimeException re){
            log.error("clientsimple remove failure"+re);
        }

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> findByEntreprise(String entreprise) {
        // TODO Auto-generated method stub
        log.debug("list Cli By entreprise");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli where cli.entreprise= :entreprise");
                  q.setParameter(entreprise,entreprise); 
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> findByNom(String nom) {
        // TODO Auto-generated method stub
        log.debug("list Cli By nom");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli where cli.nom= :nom");
                  q.setParameter(nom,nom); 
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> findByPrenom(String prenom) {
        // TODO Auto-generated method stub
        log.debug("list Cli By prenom");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli where cli.prenom= :prenom");
                  q.setParameter(prenom,prenom); 
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> findByRegion(String region) {
        // TODO Auto-generated method stub
        log.debug("list Cli By region");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli where cli.regioncli= :region");
                  q.setParameter(region,region); 
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> getALL() {
        // TODO Auto-generated method stub
        log.debug("list ALL Cli");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli");                  
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @Override
    public void save(Clientsimple clientsimple) {
        // TODO Auto-generated method stub
        log.debug("save clientsimple");
        try{
            em.persist(clientsimple);
            log.debug("clientsimple saved");
        }
        catch(RuntimeException re){
            log.error("clientsimple saving failure"+re);
        }
    }

    @Override
    public void update(Clientsimple clientsimple) {
        // TODO Auto-generated method stub
        log.debug("update clientsimple");
        try{
            em.merge(clientsimple);
            log.debug("clientsimple merged");
        }
        catch(RuntimeException re){
            log.error("clientsimple merging failure"+re);
        }

    }

}

,所以我不知道如何测试这个 DAO 或其他 DAO 类?

我创建了一个主类来测试它,但它给了我一个错误(请参阅它下面的图像包含代码和控制台中的错误)。 在此处输入图像描述


下图显示了我的项目层次结构(使用的技术为 flex、spring、jpa、hibernate);
在此处输入图像描述

One of the DAO classes I implemented in a Java EE web project is under

@Repository("ClientsimpleDAO")
public class ClientsimpleDAOImp implements ClientsimpleDAO {
    private static final Log log = LogFactory.getLog(ClientsimpleDAOImp.class);
    @PersistenceContext
    EntityManager em;
    @Override
    public void delete(Clientsimple clientsimple) {
        // TODO Auto-generated method stub
        log.debug("removing clientsimple");
        try{
            em.remove(clientsimple);
            log.debug("clientsimple removed");
        }
        catch(RuntimeException re){
            log.error("clientsimple remove failure"+re);
        }

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> findByEntreprise(String entreprise) {
        // TODO Auto-generated method stub
        log.debug("list Cli By entreprise");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli where cli.entreprise= :entreprise");
                  q.setParameter(entreprise,entreprise); 
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> findByNom(String nom) {
        // TODO Auto-generated method stub
        log.debug("list Cli By nom");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli where cli.nom= :nom");
                  q.setParameter(nom,nom); 
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> findByPrenom(String prenom) {
        // TODO Auto-generated method stub
        log.debug("list Cli By prenom");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli where cli.prenom= :prenom");
                  q.setParameter(prenom,prenom); 
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> findByRegion(String region) {
        // TODO Auto-generated method stub
        log.debug("list Cli By region");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli where cli.regioncli= :region");
                  q.setParameter(region,region); 
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Clientsimple> getALL() {
        // TODO Auto-generated method stub
        log.debug("list ALL Cli");
        try{
            Query q =em.createQuery("SELECT cli from Clientsimple cli");                  
                  List<Clientsimple> cli= (List<Clientsimple>) q.getSingleResult();
            return cli;
        }catch(RuntimeException re){
            log.error(re);
            return null;
        }
    }

    @Override
    public void save(Clientsimple clientsimple) {
        // TODO Auto-generated method stub
        log.debug("save clientsimple");
        try{
            em.persist(clientsimple);
            log.debug("clientsimple saved");
        }
        catch(RuntimeException re){
            log.error("clientsimple saving failure"+re);
        }
    }

    @Override
    public void update(Clientsimple clientsimple) {
        // TODO Auto-generated method stub
        log.debug("update clientsimple");
        try{
            em.merge(clientsimple);
            log.debug("clientsimple merged");
        }
        catch(RuntimeException re){
            log.error("clientsimple merging failure"+re);
        }

    }

}

so, i don't know how can i test this dao or other ones?

i have created a main class to test it but it gives me an error(see the image under it contains code and the error in the console).
enter image description here

the following image show my project hierarchy(technologies used flex, spring, jpa, hibernate);
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里°也失望 2024-11-13 00:50:19

不要使用主类进行测试,使用 Spring 的测试框架。在 9.3 集成测试

让您的 Test 类继承自所述的 Spring 支持类之一 此处,例如 AbstractTransactionalJUnit4SpringContextTests,添加上下文配置和一些依赖项并进行一些测试。够简单的。

@ContextConfiguration("classpath:path/to/your/spring/context.xml")
public class YourServiceTest extends
       AbstractTransactionalJUnit4SpringContextTests{

    @Autowired
    private YourDaoInterfaceHere dao;

    // method is automatically transactional
    @Test
    public void testSomething(){
        dao.persist(someData);
        dao.load(someOtherData);
    }
}

关键是

  • 解耦 Spring 上下文(dao 测试将引用 daoContext.xml,但不是 everythingContext.xml
  • 使用 PropertyPlaceHolderConfigurerPropertyPlaceHolderConfigurer code>PropertyOverrideConfigurer 机制在测试和生产中使用不同的环境

顺便说一句:

catch(RuntimeException re){
       log.error("clientsimple remove failure"+re);
}

您永远不应该记录这样的异常。您正在丢失堆栈跟踪。始终使用 log.error(message, throwable) 版本。

Don't test with main classes, use Spring's test framework. Read about it in the section 9.3 Integration testing.

Let your Test class inherit from one of the Spring support classes described here, e.g. AbstractTransactionalJUnit4SpringContextTests, add the context configuration and some dependencies and do some testing. Simple enough.

@ContextConfiguration("classpath:path/to/your/spring/context.xml")
public class YourServiceTest extends
       AbstractTransactionalJUnit4SpringContextTests{

    @Autowired
    private YourDaoInterfaceHere dao;

    // method is automatically transactional
    @Test
    public void testSomething(){
        dao.persist(someData);
        dao.load(someOtherData);
    }
}

The key is to

  • decouple your spring contexts (a dao Test would reference daoContext.xml, but not everythingContext.xml)
  • use the PropertyPlaceHolderConfigurer or PropertyOverrideConfigurer mechanisms to use different environments in test and production

And as a side note:

catch(RuntimeException re){
       log.error("clientsimple remove failure"+re);
}

You should never log an exception like this. You are losing the stack trace. Always use the log.error(message, throwable) versions.

一抹苦笑 2024-11-13 00:50:19

我们的团队也遇到了这个集成问题。问题似乎是您无法真正如此严重依赖应用程序服务器/容器来对类进行单元测试。

我们最终放弃了 DAO 和 EJB 的单元测试,并使用集成测试来测试它们 - DAO 的输出是通过使用 DAO 的服务进行测试的。

Our team had this integration problem too. The problem seems to be that you can't really unit test classes so heavily relying on the application server/container.

We ended up giving up unit testing for our DAOs and EJBs and are testing them using integration tests - the output of a DAO is tested via the services that uses the DAO.

罪#恶を代价 2024-11-13 00:50:19

您的主类不会启动 Spring 上下文,因此您的 EntityManager 为 null。您必须加载 Spring 上下文,然后 Spring 将自动装配您的 EntityManager。

Your main class doesn't start a Spring context, so your EntityManager is null. You have to load your Spring context and then Spring will autowire your EntityManager.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文