Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 326
devzone Avatar asked Aug 31 '25 22:08

devzone


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:

  • Quick Guide on Loading Initial Data with Spring Boot
like image 95
Matthias Steinbauer Avatar answered Sep 03 '25 18:09

Matthias Steinbauer