Jeus
Jeus

Reputation: 486

@Sql not work @BeforeTransaction Spring Testing Annotations

@BeforeTransaction (beforeTransaction method) have to run SQL commands in start.sql after that @Commit for don't rollback database. Spring Testing Annotation

//run before test
@Commit
@Transactional
@BeforeTransaction
@Sql({"/start.sql"})//DONT WORK...
public void beforeTransaction()
{
  System.out.println("BEFORE START TRANSACTION");
}


@Test
@Commit
@Transactional
@Sql({"/delete.sql"})
public void sqlTest() {
    System.out.println("TEST RUN");
}

start.sql

SET search_path users;
-- here create default values
DELETE FROM users;
INSERT INTO users (id,name) (1,'Joe');
INSERT INTO users (id,name) (2,'Jack');
INSERT INTO users (id,name) (3,'Ellie');

delete.sql

SET search_path users;
--HERE DELETE ONE ROW
DELETE FROM users WHERE name = 'Joe';

After run tests, my database has to be in this situation.

SET search_path = users;
SELECT * FORM users;
 --------------
|   2  | Jack  |
 ------ -------
|   3  | Ellie |
 ------ -------

but that's empty (start.sql) doesn't work

Upvotes: 0

Views: 2298

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31197

@Commit, @Transactional, and @Sql are simply not supported on @BeforeTransaction and @AfterTransaction methods (or any other test lifecycle methods such as @Before, @After, etc.).

@Commit, @Transactional, and @Sql are only supported at the class level and at the @Test method level.

If you want to execute two SQL scripts for a given test method, you have to declare them together on the same test method:

@Sql({"/start.sql", "/delete.sql"})

... or:

@Sql("/start.sql")
@Sql("/delete.sql")

If you want the same scripts to be executed for every test method in the same test class, you would then annotate your test class as in the above examples

Note, however, that the presence of @Sql on a test method overrides any @Sql declarations a the class level.

If you are interested in the possibility to have class-level and method-level @Sql declarations, see this Spring issue.

Upvotes: 1

Related Questions