代码之家  ›  专栏  ›  技术社区  ›  Jaumzera

断言集合中每个元素的集成测试

  •  1
  • Jaumzera  · 技术社区  · 6 年前

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

    为了说明,考虑一个JPA类/实体,例如:

    class Person {
    
        Integer id;
        String name;
        String lastName;
        Address address;
        Account account;
    
    }
    

    考虑IDS Person , Address Account 会自动生成,所以我无法推断。

    任何帮助都将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  1
  •   davidxxx    6 年前

    我有三点:

    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");