To Run an sql script only one time before executing Spring boot Junit Class

Viewed 5595

I am Trying to execute an Sql file which may contain any CRUD operation(s) before executing a Spring boot Junit class/ regression Test Suite. I did it using typical/legacy JDBC way, but want to use latest API. JDBC template won't help here it seems as i am trying to run the Script. Please help me here.

1 Answers

I believe what you are trying to achieve is to pre-seed your database prior running tests. For this I usually use one of two strategies.

  1. You can put a file called data.sql into your src/main/resources or src/test/resources folder. Spring Boot will automatically pick it up and import the data into your database. If you only want to import a schema you can use schema.sql as an alternative.

  2. If you want specific data and schema loaded for tests you can always also use the @Sql annotation for that. It allows you to specify a list of SQL files to be run prior running your tests.

@Sql({"/employee_schema.sql", "/employee_test_data.sql"})
public class EmployeeTest {
    @Autowired
    private EmployeeRepository employeeRepository;

    @Test
    public void testLoadDataForTestClass() {
        assertEquals(3, employeeRepository.findAll().size());
    }
}

I usually refer to this excellent tutorial https://www.baeldung.com/spring-boot-data-sql-and-schema-sql

Related