Video in progress
How do you test code that works with @TransactionalEventListener(phase = AFTER_COMMIT)?
Because the test transaction ends with a rollback, an AFTER_COMMIT listener is never called at all. Either I write the test without @Transactional and wait for the result, or I commit inside the test with TestTransaction.flagForCommit() and TestTransaction.end(), then check the listener's effect.
📖 Answer
The situation: after a payment is confirmed, a PaymentConfirmed event is published, and the listener sends an email after the commit and activates the subscription. The test is written with @Transactional, and it isn't green because the email never goes out. Some people then switch the listener to @EventListener, and in prod the email starts going out even for payments that were rolled back.
Committing inside the test:
@SpringBootTest
@Transactional
class PaymentConfirmIT {
@Autowired PaymentService payments;
@MockitoBean EmailSender email;
@Test
void emailGoesOnlyAfterCommit() {
payments.confirm(42L);
verifyNoInteractions(email); // no commit yet
TestTransaction.flagForCommit();
TestTransaction.end(); // the commit and the listener happen here
verify(email).sendReceipt(42L);
}
}
TestTransaction works only while a test-managed transaction is open. The committed data stays in the database, so you must clean it up in @AfterEach.
If you only need to check that the event was published, @RecordApplicationEvents is handier:
@Autowired ApplicationEvents events;
// ...
assertThat(events.stream(PaymentConfirmed.class)).hasSize(1);
Write the opposite case too: if the service throws an exception, the transaction rolls back and the listener isn't called. AFTER_COMMIT was chosen for exactly that behavior, so it should be pinned down in a test as well. If the listener is @Async, you wait with Awaitility instead of verify.
Sign up to mark studied questions and save your progress.