Search code examples
hibernateunit-testingquarkusquarkus-panache

Best practice for writing unit tests for Quarkus Panache entities


I'm working on a project using the Quarkus framework, and I've implemented some entities using Quarkus Panache for my data persistence layer. Now, I'm trying to write unit tests to ensure the integrity of my data operations, particularly focusing on testing relations between entities and the cascading behavior when deleting individual entities.

Here's a simplified example of an entity structure:

@Entity
public class Author extends PanacheEntity {
    @Column(unique = true, nullable = false)
    public String name;
    // ...
}

@Entity
public class Book extends PanacheEntity {

    public String title;

    @OneToMany(
            cascade = CascadeType.PERSIST,
            orphanRemoval = true)
    public Author author;
    // ...
}

I find dozens of examples on how to test endpoints and services, and I'm aware that this is the regular way to test. However, I often encounter errors related to the relationships of my entities and want to find a way to effectivly test my data structure.


Solution

  • You can’t unit test an Entity, you need an IT test:

    @QuarkusTest
    class EntityTest
    
    @Test
    @TestTransaction
    void crud(){
      var author=new Author();
      author.persist();
      // etc.
      var authors= Author.list();
    }
    

    See also: https://quarkus.io/guides/getting-started-testing#tests-and-transactions