Spring boot 测试是否在SpringDataJPatest中加载了集合
我在测试SpringDataJPatest中是否加载了集合时遇到问题 为此,我创建了一个实体,其id和项目列表如下所示。列表应该是延迟加载的(所以我假设它不应该在测试中加载)Spring boot 测试是否在SpringDataJPatest中加载了集合,spring-boot,spring-data-jpa,Spring Boot,Spring Data Jpa,我在测试SpringDataJPatest中是否加载了集合时遇到问题 为此,我创建了一个实体,其id和项目列表如下所示。列表应该是延迟加载的(所以我假设它不应该在测试中加载) @数据 @实体 @表(name=“示例”) 公开课范例{ @身份证 @GeneratedValue(策略=GenerationType.IDENTITY) 保护长id; @OneToMany(mappedBy=“example”,cascade=CascadeType.ALL,fetch=FetchType.LAZY) 私
@数据
@实体
@表(name=“示例”)
公开课范例{
@身份证
@GeneratedValue(策略=GenerationType.IDENTITY)
保护长id;
@OneToMany(mappedBy=“example”,cascade=CascadeType.ALL,fetch=FetchType.LAZY)
私人名单收集;
}
存储库代码如下所示:
@Repository
public interface ExampleRepository extends PagingAndSortingRepository<Example, Long> {
@Query("SELECT e FROM Example e")
List<Example> findAllActive();
}
@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
}
@存储库
公共接口示例存储库扩展了分页和排序存储库{
@查询(“从示例e中选择e”)
List findAllActive();
}
在测试中,我创建了一个新的示例实体,生成集合,将实体保存到数据库中,然后从数据库中获取实体,并检查集合是否已初始化。
测试代码如下所示:
@Repository
public interface ExampleRepository extends PagingAndSortingRepository<Example, Long> {
@Query("SELECT e FROM Example e")
List<Example> findAllActive();
}
@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
}
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace=replace.NONE)
公共类示例RepositoryTest{
@自动连线
私有示例库;
@试验
公共无效myTest(){
示例=新示例();
示例.setCollection(Utils.generateCollection())
保存(示例);
List actives=repository.findAllActive();
//在循环中测试集合是否已初始化,该集合应返回false
}
我尝试了以下方法:
- 注入TestEntityManager并使用
从那里获取PersistenceUnitUtil,并调用em.getEntityManager().getEntityManager工厂().getPersistenceUnitUtil()
和isLoaded(actives.get(0.getCollection())
方法,两者都返回trueisLoaded(actives.get(0),“collection”)
- 调用
和Hibernate.isInitialized(actives.get(0).getCollection())
方法,这两个方法都返回trueHibernate.isPropertyInitialized(actives.get(0),“collection”)
- 检查集合包含的内容-它是一个包含元素的PersistentBag。我希望它改为null
我遗漏了什么?我遇到了类似的问题,我无法复制spring JPA行为w.r.t.惰性加载集合,因为在我的测试中,我所有的实体对象都被急切地加载。你找到了解决方案吗?@MichielHaisma遗憾的是没有