7

测试 DAO 层的正确方法是什么?

我在创建和销毁的地方拥有@BeforeMethod@AfterMethod注释了方法,SessionFactory但它不适用于多个测试。如果测试是一个接一个地运行,但是当它们一起运行时没有使用 maven 构建,所以我决定我应该使用 TestNg 组对它们进行分组,并在我用 Hibernate 做同样事情的地方做@BeforeGroup和方法。@AfterGroup

所以我做了这样的事情:

@Test(groups = {"integration"})
public class IntegrationTest
{
    protected SessionFactory sessionFactory;

    @BeforeGroups(groups = {"integration"})
    public void setUpHibernate() throws Exception
    {
        // here I configure sessionFactory
        this.sessionFactory = ...
    }

    @AfterGroups(groups = {"integration"})
    public void putItDown() throws Exception
    {
        sessionFactory.close();
    }
}

我的每个测试都像这样扩展了这个类

@Test(groups = "integration")
public class RateRepositoryHibernateTest  extends IntegrationTest
{
    ...
}

然后我注意到只有一个扩展测试sessionFactory设置和休息,null这并不奇怪,因为该方法应该运行一次。现在我真的不知道该怎么办。

如何@BeforeGroup围绕组测试方法从方法中传递数据?

或者

如何以不同的方式做到这一点?

或者

如何SessionFactory在每次测试之前和之后进行设置和拆卸,但在多次测试中不会出现任何悲观锁定异常?

- 编辑:

也欢迎解释如何以不同方式进行操作的答案。我想知道使用 TestNg、Hibernate 和一些内存数据库进行集成测试的最新技术。

——编辑2:

堆栈跟踪,下面的测试代码

Hibernate: select roomtype_.type_name from ROOM_TYPES roomtype_ where roomtype_.type_name=?
Hibernate: call next value for rates_sequence
Hibernate: call next value for rates_sequence
Hibernate: insert into ROOMS (prefix, housekeepingStatus, availability, maxExtraBeds, standard, maximum, type, name) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into RATES (standardPrice, upchargeExtraPerson, upchargeExtraBed, room, RATE_TYPE, id) values (?, ?, ?, ?, 'R', ?)
Hibernate: insert into RATES (standardPrice, upchargeExtraPerson, upchargeExtraBed, room, seasonId, RATE_TYPE, id) values (?, ?, ?, ?, ?, 'S', ?)
Hibernate: insert into ROOM_TYPES (type_name) values (?)
Hibernate: select roomtype_.type_name from ROOM_TYPES roomtype_ where roomtype_.type_name=?
Hibernate: call next value for rates_sequence
Hibernate: insert into ROOMS (prefix, housekeepingStatus, availability, maxExtraBeds, standard, maximum, type, name) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into RATES (standardPrice, upchargeExtraPerson, upchargeExtraBed, room, RATE_TYPE, id) values (?, ?, ?, ?, 'R', ?)
org.hibernate.PessimisticLockException: Timeout trying to lock table ; SQL statement:
insert into RATES (standardPrice, upchargeExtraPerson, upchargeExtraBed, room, RATE_TYPE, id) values (?, ?, ?, ?, 'R', ?) [50200-168]
    at org.hibernate.dialect.H2Dialect$2.convert(H2Dialect.java:317)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at $Proxy13.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2962)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3403)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:275)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1210)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:399)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
    at net.mklew.hotelms.persistance.RatesPersistanceTest.should_save_rates_and_retrieve_them_with_success(RatesPersistanceTest.java:80)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:673)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:842)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1166)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.runWorkers(TestRunner.java:1178)
    at org.testng.TestRunner.privateRun(TestRunner.java:757)
    at org.testng.TestRunner.run(TestRunner.java:608)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1158)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1083)
    at org.testng.TestNG.run(TestNG.java:999)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:203)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:174)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:111)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.h2.jdbc.JdbcSQLException: Timeout trying to lock table ; SQL statement:
insert into RATES (standardPrice, upchargeExtraPerson, upchargeExtraBed, room, RATE_TYPE, id) values (?, ?, ?, ?, 'R', ?) [50200-168]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
    at org.h2.message.DbException.get(DbException.java:158)
    at org.h2.command.Command.filterConcurrentUpdate(Command.java:276)
    at org.h2.command.Command.executeUpdate(Command.java:232)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:156)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:142)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
    ... 47 more
Caused by: org.h2.jdbc.JdbcSQLException: Concurrent update in table "PRIMARY_KEY_4": another transaction has updated or deleted the same row [90131-168]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
    at org.h2.message.DbException.get(DbException.java:169)
    at org.h2.message.DbException.get(DbException.java:146)
    at org.h2.table.RegularTable.addRow(RegularTable.java:146)
    at org.h2.command.dml.Insert.insertRows(Insert.java:124)
    at org.h2.command.dml.Insert.update(Insert.java:84)
    at org.h2.command.CommandContainer.update(CommandContainer.java:75)
    at org.h2.command.Command.executeUpdate(Command.java:230)
    ... 54 more

测试代码:

public class RatesPersistanceTest
{

    protected SessionFactory sessionFactory;
    protected HibernateSessionFactory hibernateSessionFactory;

    @BeforeMethod
    public void setUpHibernate() throws Exception
    {
        Logger logger = mock(Logger.class);
        NativelyConfiguredHibernateSessionFactory hibernateSessionFactory = new
                NativelyConfiguredHibernateSessionFactory(logger);
        this.sessionFactory = hibernateSessionFactory.getSessionFactory();
        this.hibernateSessionFactory = hibernateSessionFactory;
    }

    @AfterMethod
    public void putItDown() throws Exception
    {
        sessionFactory.close();
    }

    @Test
    public void should_save_rates_and_retrieve_them_with_success()
    {
        // given
        Money standardPrice = Money.parse("USD 85");
        Money upchargeExtraPerson = Money.parse("USD 80");
        Money upchargeExtraBed = Money.parse("USD 75");
        RoomType roomType = getMeRoomType();
        Room room = getMeRoom(roomType);

        AvailabilityPeriod availabilityPeriod = new AvailabilityPeriod(DateTime.now(), DateTime.now().plusDays(5),
                true);
        Season season = new BasicSeason("season name", availabilityPeriod);
        Rate seasonRate = new SeasonRate(standardPrice, upchargeExtraPerson, upchargeExtraBed, room, season);

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        session.save(roomType);
//        session.save(room);

        session.getTransaction().commit();
        session.close();


        session = sessionFactory.openSession();
        session.beginTransaction();

        //        session.save(roomType);
        session.save(room);

        session.getTransaction().commit();
        session.close();

        session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(season);

        session.save(seasonRate);

        session.getTransaction().commit();
        session.close();
        // when
        session = sessionFactory.openSession();
        session.beginTransaction();
        final List<Rate> list = session.createQuery("from Rate").list();

        // then
        assertThat(list).contains(seasonRate);
        session.getTransaction().commit();
        session.close();

    }

    @Test( expectedExceptions = org.hibernate.exception.ConstraintViolationException.class)
    public void season_rate_should_violate_db_constraints_when_saved_without_season()
    {
        // given
        Money standardPrice = Money.parse("USD 85");
        Money upchargeExtraPerson = Money.parse("USD 80");
        Money upchargeExtraBed = Money.parse("USD 75");
        RoomType roomType = getMeRoomType();
        final RoomName roomName = new RoomName("103");

        final Money roomStandardPrice = Money.parse("USD 100");
        final Money roomUpchargeExtraPerson = Money.parse("USD 50");
        final Money roomUpchargeExtraBed = Money.parse("USD 20");
        final RackRate rackRate = new RackRate(roomStandardPrice, roomUpchargeExtraPerson, roomUpchargeExtraBed, null);
        final int maxExtraBeds = 2;
        final Occupancy occupancy = new Occupancy(4, 2);
        Room room = new Room("C", roomName, roomType, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE,
                maxExtraBeds, occupancy, standardPrice, upchargeExtraPerson, upchargeExtraBed);


        AvailabilityPeriod availabilityPeriod = new AvailabilityPeriod(DateTime.now(), DateTime.now().plusDays(5),
                true);
        Season season = new BasicSeason("season name", availabilityPeriod);
        Rate seasonRate = new SeasonRate(standardPrice, upchargeExtraPerson, upchargeExtraBed, room, null);

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        session.save(room);
        // when
        session.save(seasonRate);

        session.getTransaction().commit();
        session.close();
        // then exception should be thrown
    }

//    @Test
//    public void package_rate_should_violate_db_constraints_when_saved_without_package()
//    {
//
//    }

    private RoomType getMeRoomType()
    {
        final RoomType roomType = new RoomType("cheap" + DateTime.now().toString());
        return roomType;
    }

    private Room getMeRoom(RoomType roomType)
    {
        final RoomName roomName = new RoomName("101001" + DateTime.now().toString());

        final Money standardPrice = Money.parse("USD 100");
        final Money upchargeExtraPerson = Money.parse("USD 50");
        final Money upchargeExtraBed = Money.parse("USD 20");
        final RackRate rackRate = new RackRate(standardPrice, upchargeExtraPerson, upchargeExtraBed, null);
        final int maxExtraBeds = 2;
        final Occupancy occupancy = new Occupancy(4, 2);
        return new Room("C", roomName, roomType, HousekeepingStatus.CLEAN, RoomAvailability.AVAILABLE, maxExtraBeds,
                occupancy, standardPrice, upchargeExtraPerson, upchargeExtraBed);
    }

}

休眠配置:

<hibernate-configuration>

    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=0;MVCC=true</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"/>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create-drop</property>

       <!-- skipped mappings -->

    </session-factory>

</hibernate-configuration>
4

2 回答 2

3

我首选的测试使用 Hibernate 的代码的方法是使用@BeforeMethod@AfterMethod测试方法。我对TestNg 没有任何经验,但我认为它处理这些函数的方式类似于JUnit3.8.1 对setUp() 和tearDown() 所做的,这是我使用的。

对我来说,关键点是单元测试执行顺序无关紧要的想法。如果您使用@BeforeGroupand @AfterGroup,那么您拥有相同的SessionFactory实例,因此具有相同的数据库(在内存中或不在内存中),并且运行测试的任何变异操作SessionFactory都会影响以后执行读取操作的测试。这可能是需要的(尽管顺序可能必须是可预测的),在这种情况下,您实际上是在谈论单个“集成测试”,但对于您的情况,听起来您希望测试是独立的。

下一个问题是如何做到这一点。我所做的是将 Hibernate 配置为创建并连接到内存数据库,在其上运行创建模式脚本,并为每个测试方法创建一个 SessionFactory。

@Override
protected void setUp() throws Exception {
    super.setUp();
    String dialectClassName = HSQLDialect.class.getName();
    AnnotationConfiguration config = new AnnotationConfiguration().addAnnotatedClass(DividendScheduleGeneratorImpl.class);

    config.setProperty(Environment.DIALECT, dialectClassName);
    config.setProperty(Environment.DRIVER, jdbcDriver.class.getName());
    config.setProperty(Environment.URL, "jdbc:hsqldb:mem:testDB");
    config.setProperty(Environment.USER, "SA");
    config.setProperty(Environment.PASS, "");

    SchemaExport export = new SchemaExport(config);
    export.create(false, true);

    sessions = config.buildSessionFactory();
}

@Override
protected void tearDown() throws Exception {
    sessions.close();
    sessions = null;

    super.tearDown();
}

几点注意事项:

  1. 架构创建并不是那么快,至少对于我使用的 HSQLDB。但是,只要您将真正测试 Hibernate 的测试与使用可模拟持久层的测试完全分开,就应该没问题,因为不会有那么多测试必须使用实际数据库。
  2. 我的测试是单线程运行的。如果您正在运行多线程,则需要设置数据库名称,以便它对于并发运行的测试是唯一的。

编辑:

根据您的错误堆栈跟踪和代码,以及测试独立运行的事实,我怀疑 PessimisticLockExceptions 是由针对同一数据库在不同线程上运行的测试引起的。您甚至可能在 RATES 表上有一个以数据库为中心的死锁。处理它的两个选项是让测试生成独立的数据库,或者告诉 TestNG 串行运行测试。

首先,您必须以编程方式编辑 Hibernate 连接字符串

jdbc:h2:mem:db1;DB_CLOSE_DELAY=0;MVCC=true

jdbc:h2:mem:<TESTNAME>;DB_CLOSE_DELAY=0;MVCC=true

或类似的。在 JUnit 中,我会使用TestCase.getName(),我假设 TestNG 中有类似的可用功能。

另一种方法是串行运行。根据TestNG文档,应该可以通过注释类(而不是方法)来序列化测试以添加@Test(singleThreaded=true)

@Test(singleThreaded=true)
public class RatesPersistanceTest

至少它应该是这样工作的,也许当你尝试它时,你注释了这个方法?

于 2013-01-23T19:09:03.453 回答
0

已经使用AbstractTestNGSpringContextTests.

@ContextConfiguration(locations = { "file:src/test/resources/test-context.xml" })
@TransactionConfiguration(defaultRollback = true)
public class TheDAOTest extends AbstractTestNGSpringContextTests {

    private static final Logger LOG = Logger.getLogger(TheDAOTest.class);

    // N.B. this will be wired AFTER @BeforeTest !!
    @Autowired TheDAO subject;

    @BeforeMethod
    public void beforeMethod() {
        final HibernateTemplate ht = subject.getHibernateTemplate();
        ht.deleteAll(subject.listCustomers());
    }

    @Test
    public void noCustomers() {
        final List<CustomerDTO> customers = subject.listCustomers();
        assert customers != null : "listCustomers null result";
        LOG.info("listCustomers: " + customers);
        assert customers.size() == 0 : "Expected zero customers";

        final CustomerDTO customer = subject.findCustomerById(0L);
        assert customer == null : "Unexpected customer found";
    }

    @Test
    public void saveAndFind() {
        final CustomerDTO dto1 = makeDTO("0");
        final CustomerDTO saved = subject.save(dto1);
        assert saved != null ;

        final Long id1 = saved.getId();
        CustomerDTO customer = subject.findCustomerById(id1);
        assert customer != null ;
        assert customer.getId().equals(id1);
        assert customer.getTN().equals(dto1.getTN());

        List<CustomerDTO> customers = subject.listCustomers();
        assert customers != null : "listCustomers null result";
        LOG.info("saveAndFind - listCustomers: " + customers);
        assert customers.size() == 1 : "Expected one customer";

        subject.save(makeDTO("1"));

        customer = subject.findCustomerById(id1);
        assert customer != null ;
        assert customer.getId().equals(id1);

        customers = subject.listCustomers();
        assert customers != null : "listCustomers null result";
        LOG.info("saveAndFind - listCustomers: " + customers);
        assert customers.size() == 2 : "Expected two customers";
   }

   private CustomerDTO makeDTO(final String x) {
       final CustomerDTO dto = new CustomerDTO();
       dto.setX(x);
       return dto;
   }

}

为了完整起见,DTO 是这样的:

@Entity @Table(name = "customers") public class CustomerDTO {

    @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id = Long.MIN_VALUE;
    @Column private String X;

    public Long getId() {
        return id;
    }
    public void setId(final Long id) {
        this.id = id;
    }
    public String getX() {
        return this.X;
    }
    public void setX(final String x) {
        this.X = x;
    }
    //  etc. 
}

最后,DAO:

@Component
public class TheDAO {

    public List<CustomerDTO> listCustomers() {
        return getHibernateTemplate().loadAll(CustomerDTO.class);
    }

    public CustomerDTO getCustomer(final Long id) {
        return getHibernateTemplate().get(CustomerDTO.class, id);
    }

    public List<CustomerDTO> listCustomers() {
        return getHibernateTemplate().loadAll(CustomerDTO.class);
    }

    public <T> T save(final T valueObject) {
        getHibernateTemplate().saveOrUpdate(valueObject);
        return valueObject;
    }

    public void setHibernateTemplate(final HibernateTemplate hibernateTemplate) {
        TheDAO.hibernateTemplate = hibernateTemplate;
    }

    CustomerDTO findCustomerById(final Long id) {
        return getHibernateTemplate().get(CustomerDTO.class, id);
    }

    HibernateTemplate getHibernateTemplate() {
        return TheDAO.hibernateTemplate;
    }
}
于 2012-12-27T23:08:44.403 回答