How to execute @Sql before a @Before method

喜你入骨 提交于 2019-11-27 19:26:43

By default, any SQL scripts executed via @Sql will be executed before any @Before methods. So the behavior you are experiencing is correct, but you can change the execution phase via the executionPhase attribute in @Sql (see example below).

If you want to execute multiple scripts, that is also possible via @Sql.

So if you have a clean-up script named clean-parametro.sql that deletes from the PARAMETRO table, you could annotate your test method like the following (instead of invoking JdbcTestUtils.deleteFromTables() in your @Before method).

@Test
@Sql({"dml-parametro.sql", "clean-parametro.sql"})
public void test() { /* ... */ }

Of course, if dml-parametro.sql inserts values into the PARAMETRO table, then it likely does not make sense to immediately delete those values in the clean-up script.

Please note that @Sql and @SqlConfig provide multiple levels of configuration for script execution.

For example, if you want to create tables before your test and clean up after your test, you could do something like this on Java 8:

@Test
@Sql("create-tables.sql")
@Sql(scripts = "clean-up.sql", executionPhase = AFTER_TEST_METHOD)
public void test() { /* ... */ }

Or use @SqlGroup as a container on Java 6 or Java 7:

@Test
@SqlGroup({
    @Sql("create-tables.sql"),
    @Sql(scripts = "clean-up.sql", executionPhase = AFTER_TEST_METHOD)
})
public void test() { /* ... */ }

If your tests are @Transactional and you'd like to clean up committed database state, you can instruct Spring to execute your clean-up SQL script in a new transaction like this:

@Test
@Sql("insert-test-data.sql")
@Sql(
  scripts = "clean-up.sql",
  executionPhase = AFTER_TEST_METHOD,
  config = @SqlConfig(transactionMode = ISOLATED)
)
public void test() { /* ... */ }

I hope this clarifies things for you!

Cheers,

Sam (author of the Spring TestContext Framework)


Notes:

  • AFTER_TEST_METHOD is statically imported from ExecutionPhase
  • ISOLATED is statically imported from TransactionMode
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!