fedor.belov
fedor.belov

Reputation: 23323

Spring: how to execute `@Sql` within the transaction of test method?

I need the following logic:
1. Test method starts
2. Transaction opens
3. Prepare SQL file is executed
4. Test method is processed
5. Transaction rollbacks

My test class is annotated with

@SpringBootTest
@Transactional
@Rollback(true)

I tried to use @org.springframework.test.context.jdbc.Sql before test method but it doesn't work - looks like it opens a transaction, executes SQL, closes transaction (reverts it?) and after that starts test. A test doesn't see changes from SQL file

My question is: how to execute @org.springframework.test.context.jdbc.Sql within the transaction of test method? Any other way to solve this problem?

Upvotes: 7

Views: 3820

Answers (2)

johanwannheden
johanwannheden

Reputation: 952

You should have a look at the config property of the @Sql annotation, there it is possible to specify the TransactionMode to be used.

So for instance the following scripts are executed in a separate transaction ahead of entering the test method:

@Sql(
  scripts = {"classpath:file1.sql", "classpath:file2.sql"},
  config = @SqlConfig(transactionMode = TransactionMode.ISOLATED))
@Test
public void foo() { ... }

Upvotes: 12

fedor.belov
fedor.belov

Reputation: 23323

@Sql annotation works as expected. I had another problem - my tested method opened new Thread which didn't see changes from test transaction

Upvotes: 1

Related Questions