我正在尝试为 Spring Boot 应用程序编写集成测试。我有 Product 和 GalleryImage 域模型。他们是一对多的关系。
public class Product {
...
@OneToMany(mappedBy = "product")
private List<GalleryImage> galleryImages;
}
Run Code Online (Sandbox Code Playgroud)
我有一个集成测试如下:
@Test
public void testProductAndGalleryImageRelationShip() throws Exception {
Product product = productRepository.findOne(1L);
List<GalleryImage> galleryImages = product.getGalleryImages();
assertEquals(1, galleryImages.size());
}
Run Code Online (Sandbox Code Playgroud)
但是,这个测试给了我一个 LazyInitializationException。我在 Google 和 StackOverFlow 上搜索,它说会话在 productRepository.findOne(1L) 之后关闭,因为 galleryImages 是延迟加载的,所以 galleryImages.size() 给了我这个例外。
我试图在测试中添加 @Transactional 注释,但它仍然不起作用。