1

I've been working with Spring and Hibernate for about two years. Recently I have also been working on testing. Now I'm not quite sure if I understood everything correctly. Do I understand correctly that the following methods exist? **If I make wrong assumptions, please correct me!

Method 1:

Situation: The test class is annotated with @Transactional. The test data is created manually in an @BeforeEach method and stored in a repository.

Advantages: Through @Transactional annotation, all (BeforeEach, Test-Method, AfterEach) methods are executed in one transaction, which can be undone directly by rollback and therefore no emptying of the database is necessary.

Disadvantages: Since everything is carried out in one transaction and canceled directly by rollback, the data never ends up correctly in the database? Perhaps errors would occur during a commit? This means that the test does not reflect a real situation.

Method 2:

Situation: The test class has no @Transactional annotation. The test data is created and stored in an @BeforeEach method.

Advantages: Since the @Transactional annotation is missing, all calls of the service or controller are executed in a separate transaction, reflecting a real situation.

Disadvantages: Since everything is executed in separate transactions, the database must be completely emptied manually after each test (disable constraints and empty each table).

I have another question, but it's more subjective Do you like the initialization of test data using the @BeforeEach method and manual creation of objects and saving via repository or SQL scripts in @Sql annotation better? Initializing via SQL scripts feels faster in my opinion.

Sven M.
  • 587
  • 7
  • 23

0 Answers0