I have entity e.g. Product which aggregates other entities such as Category. Those entities can also aggregate other entities and so on. Now I need to test my queries to database.
For simple CRUD I would create mock of EntityManager. But what if I have more complex query which I need to test for correct functionality. Then I probably need to persist entity (or more of them) and try to retrieve/update, whatever. I would also need to persist all entities on which my Product depends.
I don’t like such approach. What is the best way to test such queries?
Thanks for replies.
Update — example
Lets assume following entity structure

This structure is maintained by JPA implementation. For example Product class would look like this
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToOne
private Category category;
@ManyToOne
private Entity1 something;
}
So now if I want to test any query used in DAO I need to create Product in database, but it is dependent on Category and Entity1 and there is @ManyToOne annotation so values cannot be null. So I need to persist those entities too, but they have also dependencies.
I’m considering pre-creating entities such Category, Entity1 and Entity2 before test using SQL script or dbunit (mentioned by @chalimartines) which would save large amount of code, but I don’t know whether it is good solution. I would like to know some best practices for such testing.
you can use
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)asupdate
You cant set the dependecies to null in order to avoid to persist them