person -> person.getFriend().getName()) .containsExactly("Brown", "Cony"); // or by field name (support nested field) assertThat(brown) .extracting("name", ”friend.name") .containsExactly("Brown", "Cony"); // or against a collection assertThat(List.of(brown, sally)) .extracting("name", ”friend.name") .containsExactly(tuple("Brown", "Cony"), tuple("Sally", null)); class Person { String name; Person friend; }
.contains(brown) // contains given item at specific index .contains(cony, atIndex(2)) // contains only these items, can repeats .containsOnly(sally, cony, brown) // contains exactly these items, in given order .containsExactly(brown, sally, cony, brown) // contains exactly these items, but in any order .containsExactlyInAnyOrder(brown, brown, cony, sally) // and more...
is(true)); assertThat(friends.get(1).getName(), is("Cony")); assertThat(friends.get(1).isBear(), is(false)); assertThat(friends.get(2).getName(), is("Sally")); assertThat(friends.get(2).isBear(), is(false)); Expected: is "Cony" but: was "Sally" // AssertJ assertThat(friends) .hasSize(3) .extracting("name", "age", "bear") .containsExactly(tuple("Brown", 18, true), tuple("Cony", 12, false), tuple("Sally", 6, false)); Actual and expected have the same elements but not in the same order, at index 1 actual element was: <("Sally", 6, false)> whereas expected element was: <("Cony", 12, false)>
execute rest of the test assertThat(sally.getName(), is("Sally")); assertThat(cony.getName(), is("Sally")); Expected: is "Sally" but: was "Brown" // AssertJ final var softly = new SoftAssertions(); softly.assertThat(brown.getName()).isEqualTo("Sally"); softly.assertThat(sally.getName()).isEqualTo("Sally"); softly.assertThat(cony.getName()).isEqualTo("Sally"); softly.assertAll(); Multiple Failures (2 failures) -- failure 1 -- Expecting: <"Brown"> to be equal to: <"Sally"> but was not. at AssertJTest.softAssertions(AssertJTest.java:104) -- failure 2 -- Expecting: <"Cony"> to be equal to: <"Sally"> but was not. at AssertJTest.softAssertions(AssertJTest.java:106)
{ // which one actually throws exception? createMockData(); methodWouldThrow(); } // need to use rule for asserting properties @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void expectExceptionWithMessage() { // which one actually throws exception? createMockData(); thrown.expect(RuntimeException.class); thrown.expectMessage(is("Err...")); methodWouldThrow(); } // AssertJ @Test void expectExceptionWithMessage() { // clear to see which is expected to throw createMockData(); assertThatThrownBy(() -> methodWouldThrow()) .isInstanceOf(RuntimeException.class) .hasMessage("Err..."); }