【发布时间】:2020-04-27 00:01:58
【问题描述】:
我为 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);
}
}
执行此操作后,城市将从数据库中删除。
我的真实测试场景:
@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);
}
}
通过我正在测试的方法完成的所有操作: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);
}
}
}
【问题讨论】:
-
在您解释
startHacDeletion的作用之前,无法判断。 -
它做了很多事情。通过更改数据库中的某些字段来更改某些域类。
-
这么多东西可能是更改没有回滚的原因。在给出更多信息之前,无法确定。
-
检查问题的更新
-
您是否在使用 Truncate 或 drop 之类的查询?
标签: java testing junit rollback micronaut