首页 > 解决方案 > Micronaut 和 JUnit 回滚

问题描述

我为 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);
        }

}
}

标签: javatestingjunitrollbackmicronaut

解决方案


我对 Micronaut 框架不是很熟悉,也不太明白@Transactional如果手动回滚更改,为什么需要注释。

但是从您的示例中可以明显看出,在第一种情况下,您使用 aconnection创建一个statement用于执行查询的,然后在相同的connection. 在第二种情况下,您connection从 中获得一个DataSource,但您没有将它传递给服务以使用它,因此如果DataSource使用某个连接池并且并不总是返回相同的连接,则服务connection将从它获得另一个,而不是那个你正在回滚。

这是我在您的代码中看到的唯一可能的问题,如果我的回答不能帮助解决您的问题,请提供一个最小的、可重现的示例


推荐阅读