Jac*_*cob 5 java testing junit rollback micronaut
我为 micronaut 微服务编写了一些测试。我希望在我的测试完成后,数据库中的所有更改都被还原(回滚)。首先,我写了一个简单的例子,它似乎有效。更改被还原。但是当我使用相同的类比运行微服务测试时,更改不会恢复。
简单的工作示例:
@Test
@Transactional
public void testRollback() {
try (Connection connection = dataSource.getConnection();
Statement stmt = connection.createStatement()){
connection.setAutoCommit(false);
stmt.execute(String.format("INSERT INTO city VALUES (9999, 'Darko town', '123')"));
connection.rollback();
} catch (SQLException e) {
Assert.fail("Exception " + e);
}
}
Run Code Online (Sandbox Code Playgroud)
执行此操作后,城市将从数据库中删除。
我的真实测试场景:
@Test
@Transactional
public void testDeleteDocuments() {
try (final Connection connection = deletionService.getDataSource().getConnection();
Statement stmt = connection.createStatement()) {
connection.setAutoCommit(false);
deletionService.startHacDeletion();
connection.rollback();
}catch (SQLException e) {
Assert.fail("Exception " + e);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在测试的方法所做的一切:DeletionService.startHacDeletion()都没有恢复。
我错过了什么吗?这是正确的方法吗?请协助....
更新:
这是删除功能
public void deleteHacDocuments () {
List<Document> allComments = new ArrayList<>();
while (hacDeletionActive) {
List<Document> parentDocuments = documentRepository.findHacDocuments();
LOG.info(String.format("Remove HAC parent documents %d", parentDocuments.size()));
for(Document document : parentDocuments){
LOG.info(String.format("Remove HAC documents %d", document.getId()));
}
if (parentDocuments.isEmpty()) {
hacDeletionActive = false;
LOG.info("HAC deletion finished");
} else {
for (Document doc : parentDocuments) {
if (doc.getType() == 1) {
deleteWholeStudy(doc.getId());
} else if (doc.getType() == 6) {
List<Document> studies = documentRepository.findStudiesByCase(doc.getId());
for (Document study : studies) {
deleteWholeStudy(study.getId());
}
deleteWholeCase(doc.getId());
} else if (doc.getType() == 4) {
allComments.add(doc);
} else {
documentService.markDocumentAsDeleted(doc.getId());
}
}
documentService.markCommentsAsDeleted(allComments);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我对Micronaut框架不是很熟悉,不太明白为什么@Transactional手动回滚更改还需要注解。
但是从您的示例中可以明显看出,在第一种情况下,您使用 aconnection创建一个statement用于执行查询的 ,然后在同一个 上调用回滚connection。在第二种情况下,您connection从 中获取一个DataSource,但您没有将其传递给服务来使用它,因此,如果DataSource使用某个连接池并且并不总是返回相同的连接,则服务将从connection中获取另一个连接,而不是那个连接你正在回滚。
这是我在您的代码中看到的唯一可能的问题,如果我的答案不能帮助解决您的问题,请提供一个最小的、可重现的示例。
| 归档时间: |
|
| 查看次数: |
825 次 |
| 最近记录: |