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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (1)

Write a response