lapkritinis
lapkritinis

Reputation: 2814

Spring boot JPA does not persist changes in single test scope

I am using Spring Boot 2.0.1 with spring-boot-starter-data-jpa.

In database I have 3 records. I perform such test:

@Test
public void shouldDeleteByName() {
    service.deleteOneByName("SOME NAME"); // Out of 3 records 1 was deleted
    List<Customer> customers = service.selectAll();
    assertThat(customers).hasSize(2); // FAILS
assertThat(customers).extracting("name").doesNotContain("SOME NAME"); // FAILS
}

There are no errors, I see that transaction is committed.

It seems that transaction either gets reverted before selectAll or selectAll doesn't see changes yet.

What I am doing wrong?

Upvotes: 0

Views: 484

Answers (1)

lapkritinis
lapkritinis

Reputation: 2814

Well it seems it solved my issue:

  1. I changed my test DB configuration transactionManager to JpaTransactionManager from DataSourceTransactionManager, example posted at the end.

  2. I annotated my service as @Transactional.

  3. I annotated my test as @Transactional (without this works, but changes are permanent). Test executes first time, but fails second time.

Code for first step WORKING ONE:

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
}

Upvotes: 1

Related Questions