在内存中使用H2数据库不会在单元测试中保留对象

时间:2015-01-26 13:01:24

标签: java unit-testing jpa h2 in-memory-database

我在persistence.xml中有关于单元测试的JPA问题。 将对象持久保存到内存中的数据库H2时会发生错误:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running some.class.MyClass
################################################################################
                    BeforeClass Start  
################################################################################
                    EntityManager is being created..  
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.541 sec <<< FAILURE!

Results :

Tests in error: 
  some.class.MyClass: getSingleResult() did not retrieve any entities

我确信存在持久性问题,而不是获取数据,因为DEV应用程序中的读取方法与真实数据库完美配合。

这是我的persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="TestPU" transaction-type="RESOURCE_LOCAL">

        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>all entities</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>

        <properties>
            <property name="eclipselink.logging.level" value="SEVERE"/>
            <!-- ALL SEVERE -->
            <property name="eclipselink.logging.level.sql" value="SEVERE"/>
            <!-- ALL SEVERE -->
            <property name="eclipselink.logging.parameters" value="true"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test;MODE=Oracle;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS DEV"/>
            <property name="javax.persistence.jdbc.user" value="sa"/>
            <property name="javax.persistence.jdbc.password" value=""/>
            <!-- model creation have to be done via javax.persistence, not hibernate/eclipselink - otherwise import doesn't works -->
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="javax.persistence.schema-generation.create-source" value="metadata"/>
            <property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
        </properties>

    </persistence-unit>
</persistence>


</persistence-unit>

这是一段Java代码:

@BeforeClass
        public static void setUpClass() {
                myOut("BeforeClass Start");
                EM = Persistence.createEntityManagerFactory(PU).createEntityManager();
                myOut("EntityManager is being created..");
                EM.persist(new Account(PU, PU, PU));
                EM.persist(new Account(PU + "2", "dsaddsa", "dsadas"));
                EM.persist(new Account(PU + "3", "saddsd", "dsadasa"));
                EM.persist(new Account(PU + "4", "adsada", "hdsd"));

                final DaoLogged dao = new DaoLogged();
                dao.setEntityManager(EM);
                dao.getAccountByLogin(PU);
                myOut("BeforeClass Done.");
        }

SingleResult方法:

public Account getAccountByLogin(String login) {
                return (Account) getEntityManager().createNamedQuery("Account.findByLogin").setParameter("login", login).getSingleResult();
}

我将不胜感激任何帮助! :) 此致!

[编辑]

我一直在寻找答案,实际上在今天的早上,这完全没有用,但经过几个小时的编辑,在网上搜索我坚持了这个......

[编辑2]

我已将上述方法更改为:

@BeforeClass
        public static void setUpClass() {
                myOut("BeforeClass Start");
                EM = Persistence.createEntityManagerFactory(PU).createEntityManager();
                myOut("EntityManager is being created..");

                **EM.getTransaction().begin();**

                EM.persist(new Account(PU, PU, PU));
                EM.persist(new Account(PU + "2", "dsaddsa", "dsadas"));
                EM.persist(new Account(PU + "3", "saddsd", "dsadasa"));
                EM.persist(new Account(PU + "4", "adsada", "hdsd"));
                **EM.getTransaction().commit();
                EM.flush();
                EM.getTransaction().begin();**
                final DaoLogged dao = new DaoLogged();
                dao.setEntityManager(EM);
                dao.getAccountByLogin(PU);
                myOut("BeforeClass Done.");
        }

仍然是错误,但不同:

javax.persistence.TransactionRequiredException: 

异常说明:当前没有任何交易活动

2 个答案:

答案 0 :(得分:1)

错误表示查询未返回任何结果。确保正确设置了数据库。为此,请为EclipseLink启用DEBUG日志级别。这应该显示发送到数据库的SQL。

您还需要一个事务管理器。如何设置和配置取决于应用程序的体系结构。事务管理器负责编排事务的所有不同参与者(数据库,EntityManager,有时还有其他方(如JMS)。

如果您使用Spring,那么事务管理器将自动将事务与测试同步。

请注意,您应该尝试在每次测试之前启动事务,并在每次测试后回滚。这样,测试#2不会失败,因为测试#1在数据库中留下了垃圾。

答案 1 :(得分:0)

好的,我花了一些时间玩这些错误......:)

  1. 交易是必要的,在这种情况下flush应该在commit
  2. 之前调用
  3. 我忘了将范围test添加到POM中的eclipselink依赖项
  4. Lombok不会导致任何错误
  5. 在主要项目中形成了很好的查询(到目前为止我称之为“DEV&#39;在这里”)他们没有造成任何错误
  6. 测试中需要
  7. Sequence Generator