Test Spring Boot services. Rollback transaction with R2DBC driver

One of the most important things in the project are tests: unit, integration, and functional.

Let’s talk about implementing integration tests with DB changes rollback for applications built with Spring Boot and R2DBC driver.

When we have the application built with JDBC driver, we may use the following annotations:

@org.springframework.transaction.annotation.Transactional
@org.springframework.test.annotation.Rollback

But these annotations don’t work for the R2DBC driver. You may see in logs:

java.lang.IllegalStateException: Failed to retrieve PlatformTransactionManager for @Transactional

The reason is org.springframework.transaction.ReactiveTransactionManager extends org.springframework.transaction.TransactionManager but not org.springframework.transaction.PlatformTransactionManager

Fortunately, we may use a manual transaction management process. All we need to do is inject org.springframework.transaction.ReactiveTransactionManager bean into our test set rollback mode, and run our test inside this transaction.

@Test
void testRollback() {
StepVerifier.create(TransactionalOperator.create(reactiveTransactionManager)
.execute(status -> {
status.setRollbackOnly();
return service.update(<ENTITY>, <VALUE>);
}))
.expectNext(<UPDATED_VALUE>)
.verify();
}

Now transaction manager will roll our changes back.