Tôi đang gặp sự cố khi cố gắng đẩy các thay đổi được thực hiện trong giao dịch Hibernate đến cơ sở dữ liệu để DbUnit hoạt động đúng trong trường hợp thử nghiệm của tôi. Dường như DbUnit không nhìn thấy những thay đổi được thực hiện bởi Hibernate bởi vì họ không cam kết vào cuối của giao dịch được nêu ra ... và tôi không chắc chắn làm thế nào để cơ cấu lại trường hợp thử nghiệm của tôi để có được điều này để làm việc.Bắt DbUnit để làm việc với giao dịch Hibernate
Đây là trường hợp thử nghiệm quá đơn giản của tôi để chứng minh vấn đề của tôi: -
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:applicationContext-test.xml"
})
@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional
public class SomeTest {
@Autowired
protected DataSource dataSource;
@Autowired
private SessionFactory sessionFactory;
@Test
public void testThis() throws Exception {
Session session = sessionFactory.getCurrentSession();
assertEquals("initial overlayType count", 4, session.createQuery("from OverlayType").list().size());
//-----------
// Imagine this block is an API call, ex: someService.save("AAA");
// But for the sake of simplicity, I do it this way
OverlayType overlayType = new OverlayType();
overlayType.setName("AAA");
session.save(overlayType);
//-----------
// flush has no effect here
session.flush();
assertEquals("new overlayType count", 5, session.createQuery("from OverlayType").list().size());
// pull the data from database using dbunit
IDatabaseConnection connection = new DatabaseConnection(dataSource.getConnection());
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
QueryDataSet partialDataSet = new QueryDataSet(connection);
partialDataSet.addTable("resultSet", "select * from overlayType");
ITable actualTable = partialDataSet.getTable("resultSet");
// FAIL: Actual row count is 4 instead of 5
assertEquals("dbunit's overlayType count", 5, actualTable.getRowCount());
DataSourceUtils.releaseConnection(connection.getConnection(), dataSource);
}
}
toàn bộ ý tưởng của tôi trong việc sử dụng DbUnit là: -
- Gọi
someService.save(...)
mà lưu dữ liệu thành nhiều bảng. - Sử dụng DbUnit để nhận bảng dự kiến từ XML.
- Sử dụng DbUnit để nhận bảng thực tế từ cơ sở dữ liệu.
- Làm
Assertion.assertEquals(expectedTable, actualTable);
.
Nhưng, tại thời điểm này, tôi không thể nhận được DbUnit để xem các thay đổi được thực hiện bởi Hibernate trong giao dịch.
Tôi nên thay đổi như thế nào để DbUnit hoạt động tốt với giao dịch Hibernate?
Cảm ơn.
+1 Câu trả lời hay đấy Tomasz! – Nilesh