
在使用Spring Boot的@DataJpaTest进行数据层测试时,开发者可能会遇到一个令人困惑的现象:单个测试用例单独运行时可以顺利通过,但当所有测试用例一起运行时,部分测试却意外失败。典型的错误信息是org.opentest4j.AssertionFailedError,指出预期值与实际值在集合类型上存在差异,例如:
expected: "[com.example.recipesapi.model.Recipe@45f421c] (List12@14983265)" but was: "[com.example.recipesapi.model.Recipe@45f421c] (ArrayList@361483eb)"
这表明尽管集合中的元素内容(Recipe@45f421c)看起来是相同的,但集合的底层实现类型(如List12与ArrayList)不同,导致assertThat(...).isEqualTo(...)断言失败。List.of()在Java 9及以上版本中返回的是一个不可变列表,其具体实现类可能是内部的ImmutableCollections.ListN(或类似List12的内部类),而JPA查询结果通常返回的是可变的ArrayList或其他可变列表实现。isEqualTo在比较集合时,不仅会比较集合中的元素,有时还会检查集合的类型或顺序,从而导致这种类型不匹配的失败。
考虑以下使用@DataJpaTest的测试类,其中shouldFindSingleRecipeByName()测试在单独运行时通过,但与其他测试一起运行时失败:
@DataJpaTest
class RecipeRepositoryTest {
    @Autowired
    private RecipeRepository recipeRepositoryUnderTest;
    // 确保每个测试前清空数据,实现测试隔离
    @BeforeEach
    void tearDown() {
        recipeRepositoryUnderTest.deleteAll();
    }
    @Test
    void shouldFindSingleRecipeByName() {
        //given
        String searchName = "Tomato soup";
        Recipe recipe1 = new Recipe(1L, "Tomato soup", "Delicious tomato soup", Arrays.asList("1. "), Arrays.asList("1. "));
        Recipe recipe2 = new Recipe(2L, "Mushrooms soup", "Delicious mushrooms soup", Arrays.asList("1. "), Arrays.asList("2. "));
        List<Recipe> recipes = List.of(recipe1, recipe2); // 使用List.of()创建不可变列表
        recipeRepositoryUnderTest.saveAll(recipes);
        //when
        List<Recipe> recipesList = recipeRepositoryUnderTest.findRecipeByName(searchName.toLowerCase());
        //then
        // 这里的isEqualTo可能导致类型不匹配问题
        assertThat(recipesList).isEqualTo(List.of(recipe1)); 
    }
    // 其他测试方法...
}解决此类问题主要有两种策略:一是使用更灵活的断言方法,二是统一集合类型。
AssertJ等断言库提供了多种用于集合比较的方法,它们更侧重于集合的元素内容而非其具体实现类型。
示例代码:
import static org.assertj.core.api.Assertions.assertThat;
// ...
@Test
void shouldFindSingleRecipeByName_UsingContainsExactly() {
    // ... (given 和 when 部分保持不变)
    //then
    // 推荐使用 containsExactly 比较集合内容
    assertThat(recipesList).containsExactly(recipe1); 
}
@Test
void shouldFindTwoRecipesByName_UsingContainsExactlyInAnyOrder() {
    // ... (given 和 when 部分保持不变)
    //then
    // 如果顺序不重要,可以使用 containsExactlyInAnyOrder
    assertThat(recipesList).containsExactlyInAnyOrder(recipe1, recipe2);
}注意事项:containsExactly和containsExactlyInAnyOrder更专注于比较集合的逻辑内容(即其中的元素),而不是集合对象的引用或其具体实现类。这使得测试更具鲁棒性,不易受底层集合类型变化的影响。
如果坚持使用isEqualTo,可以通过将预期的集合转换为与实际结果更可能匹配的类型来解决。通常,JPA查询返回的是ArrayList或其他可变列表。
示例代码:
import java.util.ArrayList;
import java.util.List;
// ...
@Test
void shouldFindSingleRecipeByName_StandardizingCollectionType() {
    // ... (given 和 when 部分保持不变)
    //then
    // 将预期的List.of()结果包装成ArrayList
    assertThat(recipesList).isEqualTo(new ArrayList<>(List.of(recipe1))); 
}注意事项: 这种方法强制了预期结果的集合类型,使其与实际结果的类型保持一致,从而满足isEqualTo可能进行的类型检查。然而,这增加了代码的冗余,且不如containsExactly系列方法直观。通常情况下,推荐使用containsExactly或containsExactlyInAnyOrder。
虽然上述问题直接与集合断言有关,但测试中涉及到的实体类Recipe的equals和hashCode方法实现对于集合的正确比较至关重要。assertThat在比较集合元素时,会依赖这些元素的equals方法。
原始Recipe类的equals和hashCode实现:
@Override
public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
    final Recipe recipe = (Recipe) o;
    return id != null && Objects.equals(id, recipe.id);
}
@Override
public int hashCode() {
    return getClass().hashCode(); // ⚠️ 潜在问题:与equals不一致
}问题分析:equals方法基于id字段进行比较,这是推荐的做法(尤其对于JPA实体,通常基于主键)。然而,hashCode方法只返回getClass().hashCode()。根据Java规范,如果两个对象equals返回true,那么它们的hashCode也必须相等。当前实现违反了这一约定。两个具有相同id但不同实例的Recipe对象,如果getClass().hashCode()返回不同值,将导致在基于哈希的集合(如HashSet, HashMap的键)中行为异常,甚至影响某些断言的准确性。
推荐的hashCode实现: 为了保持equals和hashCode的一致性,hashCode应该基于equals方法中使用的字段(即id)。
import java.util.Objects;
// ...
@Override
public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
    final Recipe recipe = (Recipe) o;
    // 对于JPA实体,通常只比较ID即可
    return id != null && Objects.equals(id, recipe.id);
}
@Override
public int hashCode() {
    // 与equals方法保持一致,基于id字段计算哈希值
    return Objects.hash(id); 
}重要性: 尽管List.of()与ArrayList的类型差异是导致原始断言失败的直接原因,但正确实现equals和hashCode是Java对象比较和集合操作的基石,尤其在处理JPA实体时,它能确保对象在各种集合和断言场景下的行为符合预期。
在@DataJpaTest中遇到集合断言失败,特别是当isEqualTo方法在单独和批量运行测试时表现不一致时,通常是由于预期集合与实际集合的底层实现类型不匹配造成的。
通过遵循这些指导原则,可以编写出更稳定、更准确的JPA层测试代码,有效避免因集合类型差异导致的断言失败问题。
以上就是解决DataJpaTest中集合断言失败:理解isEqualTo与集合类型差异的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号