使集合中的每个元素有效的集成测试

时间:2018-10-19 18:37:35

标签: spring-boot jpa integration-testing junit4

考虑使用带有Spring-Boot和JUnit的IT来测试从数据库返回的集合是否包含所有需要的元素。最好的方法是什么?

为说明起见,请考虑以下JPA类/实体:

class Person {

    Integer id;
    String name;
    String lastName;
    Address address;
    Account account;

}

考虑到PersonAddressAccount的ID是自动生成的,因此我无法推断它们。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认同3分:

1)调用要测试的方法,该方法使用专用于您的实体的JpaRepository保存并刷新实体实例

2)确保您的集成测试可靠/有价值
在这里,有必要清除JPA(EntityManager.clear())的一级缓存以测试从数据库中的实际检索。高速缓存可能会在映射中隐藏某些问题,只有在实际从数据库中找到该对象时,才会看到该问题。

3)声明预期的行为,该行为将从数据库中检索已保存的实体,并根据您的期望声明其状态。

对于声明对象的字段,AssertJ可能会引起您的兴趣。
它不会强制您覆盖equals()/hashCode(),这非常简单且有意义。
当您要声明嵌套对象时,我建议按对象使用不同的assertThat()
 例如:

Person person = new Person()...;
// action
personRepository.saveAndFlush(person);

// clear the first level cache
em.clear();

// assertions
Optional<Person> optPerson = personRepository.findById(person.getId());

// JUnit
Assert.assertTrue(optPerson.isPresent()); 
// AssertJ
person = optPerson.get();
Assertions.assertThat(person)
          .extracting(Person::getName, Person::getLastName)                     
          .containsExactly("expected name", "expected last name");

Assertions.assertThat(person.getAccount())
          .extracting(Account::getFoo, Account::getBar)                     
          .containsExactly("expected foo", "expected bar");

Assertions.assertThat(person.getAddress())
          .extracting(Address::getStreet, Address::getZip)                     
          .containsExactly("expected street", "expected zip");