Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute @Sql after @BeforeEach in Integration Test

currently I'm working on integration test, and this one controller cover many tables, so instead insert transactional data using @BeforeEach, I want use sql script and I tried like this..

  @Sql(scripts = {"classpath:/business-test-data.sql"})
  public class IntegrationTest extend AbstractIT {

    @BeforeEach
    void init() {
      // method from AbstractIT
      // Clear DB, Redis, Kafka, etc
    }
   
    @Test
    void someTest(){}

.. and turn out Spring executed business-test-data.sql before clear DB.

so, how can I execute business-test-data.sql after clear db? any suggestion or other approach would be appreciated. Thank you.

Notes :

  1. as for schema and master data, they already executed along with embedded postgres initialization, and I want to avoid insert transactional data using this script.
  2. Clear DB is a method inherited from AbstractIT class, change how to clear table looks like would impacted other integration test as well, so I want to avoid it too.
like image 577
Ilham Amajidi Avatar asked May 03 '26 19:05

Ilham Amajidi


1 Answers

@Sql on a class level will be executed once before the test suite is run.

@BeforeEach will be executed before each test method.

So It looks like you need your @Sql to run before each method as well. you can either do it manually in the same method or annotate methods with @Sql instead (so not at class level but at method level)

See more here: Quick Guide on Loading Initial Data with Spring Boot - @Sql

like image 169
asgarov1 Avatar answered May 06 '26 12:05

asgarov1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!