Search code examples
javaquarkusquarkus-panachequarkus-reactivequarkus-testing

Quarkus Reactive testing with database operation leading to java.lang.IllegalStateException: No current Vertx context found


I'm trying to test a part of my code that does a database transaction.

@QuarkusTest
class MyServiceTest {

    @InjectSpy
    MyService myService;

    @Test
    void testDatabaseOperation() {
        myService.doSomeDatabaseOperation()
                .invoke(i -> Assertions.assertEquals(0, i.size()))
                .subscribe().withSubscriber(UniAssertSubscriber.create())
                .assertCompleted();
    }

But I'm getting this exception when trying to call .find() of my repository

java.lang.IllegalStateException: No current Vertx context found

Why is there no session created automatically and how would I tell Quarkus to do so?


Solution

  • Found out you need to write your tests slightly different and let Quarkus inject an UniAsserter object, allowing you to do async assertions.

    @QuarkusTest
    class MyServiceTest {
    
        @InjectSpy
        MyService myService;
    
    
        @Test
        @RunOnVertxContext
        void testDatabaseOperation(UniAsserter a) {
            final var asserter = new TransactionalUniAsserterInterceptor(a);
    
            asserter.assertNotNull(() -> myService.doSomeDatabaseOperation());
        }
    
    }
    

    Additional wrapper that opens transactions

    public class TransactionalUniAsserterInterceptor extends UniAsserterInterceptor {
    
        public TransactionalUniAsserterInterceptor(UniAsserter asserter) {
            super(asserter);
        }
    
        /**
         * Assert/execute methods are invoked within a database transaction
         */
        @Override
        protected <T> Supplier<Uni<T>> transformUni(Supplier<Uni<T>> uniSupplier) {
            return () -> Panache.withTransaction(uniSupplier);
        }
    }