Search code examples
javaspringspring-dataspring-data-r2dbc

How to run query like @Sql for test in Spring Data R2DBC


I created a Repository and writing a Test Case. I want to run insert.sql before executing the test method with @Sql (org.springframework.test.context.jdbc) but it doesn't run. Is there another way?


Solution

  • I faced the same issue, Spring Data R2DBC doesn't support @SQl annotation yet.

    Use the function below:

        private void executeSqlScriptBlocking(final Resource sqlScript) {
            Mono.from(connectionFactory.create())
                    .flatMap(connection -> ScriptUtils.executeSqlScript(connection, sqlScript)
                            .then(Mono.from(connection.close())))
                    .block();
        }
    

    Then:

        @Autowired
        private ConnectionFactory connectionFactory;
    
        @BeforeEach
        void init(@Value("classpath:init_test_data.sql") Resource sqlScript) {
            executeSqlScriptBlocking(sqlScript);
        }
    

    application.yml:

    spring:
      r2dbc:
        pool:
          enabled: true
          initial-size: 8
          max-size: 16
    

    When connection pool in used in tests, we should close every created connection because it seems to be not released. Example, if we have 16 pool size, we'll be able to execute only 16 tests then get an infinite loop started from 17th.

    Tested on:

    Java: 8(jdk-8.0.272.10-hotspot)
    Spring Boot: 2.3.9
    JUnit 5: 5.6.3