jeudi 9 janvier 2020

Micronaut and JUnit rollback

I have some tests written for a micronaut micro service. I would want that after my tests are done all the changes in the DB are reverted (rollback). Firstly I have written a simple example which seems to work. Changes are reverted. But when I run a micro service test using the same analogy the changes are not reverted.

Simple working example:

@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);
    }
}

After this is executed the city is removed from the DB.

My real test scenario:

@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);
    }

}

Everything done by the method I am testing: DeletionService.startHacDeletion() is not reverted.

Am I missing something? Is this the right approach? Please assist....

UPDATE:

here is the delete function

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

}
}

Aucun commentaire:

Enregistrer un commentaire