jeudi 26 juillet 2018

Spring @Transactional does not rollback when under test

I'm using Spring Data JPA and have a method annotated with @Transactional. It works when the app is actually running, but I want to write a test for it.

public interface FooJpaRepository extends JpaRepository<Foo, UUID> {}

public class FooService {

  private final FooJpaRepository repo;

  @Transactional
  public void saveAndFail() {
    Foo foo = new Foo();
    repo.save(foo);
    throw new RuntimeException("uh oh, something went wrong");
  }

  public FooService(FooJpaRepository repo) {
    this.repo = repo;
  }
}

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase
public class FooTest {

@Autowired
FooJpaRepository repo;

  @Test
  public void shouldRollBack() {
    repo.deleteAll();
    FooService service = new FooService(repo);
    try {
      service.saveAndFail();
    } catch (RuntimeException e) {
      //expected
    }
    assertEquals(0, repo.findAll().size());//fails, expected 0 actual 1
  }
}

Why?

Aucun commentaire:

Enregistrer un commentaire