AssertJ:containsOnly和containsExactlyInAnyOrder之间有什么区别

问题描述 投票:2回答:1

AbstractIterableAssert#containsOnly说:

验证实际组是否仅按任何顺序包含给定值而不包含任何其他值。

AbstractIterableAssert#containsExactlyInAnyOrder说:

验证实际组是否包含完全给定的值,而不是任何其他顺序。

描述看起来几乎相同,那么唯一和确切的实际区别是什么?

list unit-testing junit assert assertj
1个回答
6
投票

只有当预期和实际的集合/列表包含重复项时,实际差异才有意义:

  • containsOnly总是重复不敏感:如果匹配预期/实际值的集合,它永远不会失败
  • containsExactlyInAnyOrder总是重复敏感:如果预期/实际元素的数量不同,它就会失败

虽然如果:

  • 实际集合中至少缺少一个预期的唯一值
  • 并非所有来自实际集合的唯一值都被声明

看例子:

private List<String> withDuplicates;
private List<String> noDuplicates;

@Before
public void setUp() throws Exception {
    withDuplicates = asList("Entryway", "Underhalls", "The Gauntlet", "Underhalls", "Entryway");
    noDuplicates = asList("Entryway", "Underhalls", "The Gauntlet");
}

@Test
public void exactMatches_SUCCESS() throws Exception {
    // successes because these 4 cases are exact matches (bored cases)
    assertThat(withDuplicates).containsOnly("Entryway", "The Gauntlet", "Underhalls", "Entryway", "Underhalls"); // 1
    assertThat(withDuplicates).containsExactlyInAnyOrder("Entryway", "The Gauntlet", "Underhalls", "Entryway", "Underhalls"); // 2

    assertThat(noDuplicates).containsOnly("Entryway", "The Gauntlet", "Underhalls"); // 3
    assertThat(noDuplicates).containsExactlyInAnyOrder("Entryway", "The Gauntlet", "Underhalls"); // 4
}

@Test
public void duplicatesAreIgnored_SUCCESS() throws Exception {
    // successes because actual withDuplicates contains only 3 UNIQUE values
    assertThat(withDuplicates).containsOnly("Entryway", "The Gauntlet", "Underhalls"); // 5

    // successes because actual noDuplicates contains ANY of 5 expected values
    assertThat(noDuplicates).containsOnly("Entryway", "The Gauntlet", "Underhalls", "Entryway", "Underhalls"); // 6
}

@Test
public void duplicatesCauseFailure_FAIL() throws Exception {
    SoftAssertions.assertSoftly(softly -> {
        // fails because ["Underhalls", "Entryway"] are UNEXPECTED in actual withDuplicates collection
        softly.assertThat(withDuplicates).containsExactlyInAnyOrder("Entryway", "The Gauntlet", "Underhalls"); // 7

        // fails because ["Entryway", "Underhalls"] are MISSING in actual noDuplicates collection
        softly.assertThat(noDuplicates).containsExactlyInAnyOrder("Entryway", "The Gauntlet", "Underhalls", "Entryway", "Underhalls"); // 8
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.