5

I am having troubles testing whether a collection is loaded in Spring DataJpaTest.

For that I have created an entity that has id and list of items as seen below. The list should be lazy-loaded (so I am assuming it should not be loaded in the test).

@Data
@Entity
@Table(name = "examples")
public class Example {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  protected Long id;

  @OneToMany(mappedBy = "example", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  private List<ExampleElement> collection;

}

Repository code looks like this:

@Repository
public interface ExampleRepository extends PagingAndSortingRepository<Example, Long> {

  @Query("SELECT e FROM Example e")
  List<Example> findAllActive();

}

In the test I am creating a new Example entity, generating the collection, saving the entity to database and after that getting entities from database and checking whether the collections are initialized. Test code looks like this:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class ExampleRepositoryTest {

  @Autowired
  private ExampleRepository repository;

  @Test
  public void myTest() {
    Example example = new Example();
    example.setCollection(Utils.generateCollection()))
    repository.save(example);

    List<Example> actives = repository.findAllActive();

    // tests in a loop whether the collection is initialized which should return false
  }

I have tried the following:

  • Injecting TestEntityManager and getting the PersistenceUnitUtil from there using em.getEntityManager().getEntityManagerFactory().getPersistenceUnitUtil() and calling the isLoaded(actives.get(0).getCollection()) and isLoaded(actives.get(0), "collection") methods - both return true
  • Calling Hibernate.isInitialized(actives.get(0).getCollection()) and Hibernate.isPropertyInitialized(actives.get(0), "collection") methods, which both return true as well.
  • Checking what the collection contains - it is a PersistentBag containing the elements. I expect it to be null instead.

What am I missing?

Janar
  • 2,623
  • 1
  • 22
  • 32
  • I'm having similar issues, where I cannot replicate spring JPA behaviour w.r.t. lazy-loaded collections because in my tests, all my entity objects are eagerly loaded. Did you find a solution for this? – Michiel Haisma Jun 14 '18 at 16:42
  • @MichielHaisma sadly no – Janar Jun 14 '18 at 21:38

0 Answers0