Search code examples
javajunitjunit5

junit 5 run all assert even if there is failed one


Is there any mechanism in JUnit 5 to run all assert in test even if assert in the middle failed? For example:

@Test
public void unitForTest_SomeScenario_ShouldReturn() {

    //Arrange
    var myObj = myServ.getMyObj();
    //Act & Assert
    assertThat(myObj).isNotNull();
    assertThat(myObj.getName()).isEqualTo("Steve"); //failed assert
    assertThat(myObj.getLastName()).isEqualTo("Gates");
}

My intention is to run all asserts and track that failed is only second, but not the third and first.


Solution

  • You could use JUnit5's assertAll.

    For example:

    @Test
    public void unitForTest_SomeScenario_ShouldReturn() {
        String name = "y";
        assertAll(
                () -> assertThat(name).isNotNull(),
                () -> assertThat(name).isEqualTo("x"), // failed assert
                () -> assertThat(name).isEqualTo("y"),
                () -> assertThat(name).isEqualTo("z") // failed assert
        );
    }
    

    Will fail with the following detailed response:

    Expecting:
     <"y">
    to be equal to:
     <"x">
    but was not.
    Comparison Failure: 
    Expected :x
    Actual   :y
    <Click to see difference>
    
    
    Expecting:
     <"y">
    to be equal to:
     <"z">
    but was not.
    Comparison Failure: 
    Expected :z
    Actual   :y
    <Click to see difference>
    
    org.opentest4j.MultipleFailuresError: Multiple Failures (2 failures)
    

    Note: as some of the comments on your question imply this might be better expressed by using separate tests (rather than one test with multiple assertions) however, as long as the multiple assertions are part of a single 'conceptual assertion' then I can definitely see a case for using assertAll.