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

rad*_*tao 5 junit unit-testing assert list assertj

AbstractIterableAssert#containsOnly说:

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

AbstractIterableAssert#containsExactlyInAnyOrder说:

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

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

rad*_*tao 10

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

  • 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
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 我要在`containsOnly` javadoc中澄清这个,还有一个理由. (2认同)
  • 完成https://github.com/joel-costigliola/assertj-core/blob/6983158e5ea2f6fe54c864fc0dd7ec9b672e4653/src/main/java/org/assertj/core/api/ObjectEnumerableAssert.java#L61 (2认同)