Can you have multiple assertEquals(answer, result) in the same junit test?

12,115

Solution 1

All asserts will be run, in order. The first assertion to fail causes the test to fail and no further asserts are run after that.

AssertJ has a mechanism which allows to run all assertions, whether they succeed or fail:

final SoftAssertions soft = new SoftAssertions();
soft.assertThat(...);
soft.assertThat(...);
soft.assertThat(...);
soft.assertAll();

This will report all assertions which fail on .assertAll(). Link to javadoc.


EDIT Starting with 2.0.0 (Java 7+ only) there is also AutoCloseableSoftAssertions, which means you don't need to .assertAll() at the end:

try (
    final AutoCloseableSoftAssertions soft
        = new AutoCloseableSoftAssertions();
) {
    soft.assertThat(thePope).isSaint(); // or whatever
} // <--- .assertAll() here!

Solution 2

Yes it is possible to have more than one assertEquals in one unittest. The unit test fails if one of the assertEquals returns false.

Solution 3

Hi dear i want to give you one suggestion if you want to use multiple assert then. It would be better if there is use of "if else" condition for multiple AssertTrue.

Solution 4

Yes, you can have many different assert statements inside of j/x/n Unit tests. However, as you have found, should any of the asserts fail, the entire testMethod will fail as a result.

As it so happens, inside of a testMethod the test runner will begin executing the assert statements. As soon as one fails the testMethod will return, not executing any additional asserts.

Share:
12,115
Andrejs Bicevskis
Author by

Andrejs Bicevskis

Updated on August 21, 2022

Comments

  • Andrejs Bicevskis
    Andrejs Bicevskis almost 2 years

    Doing some junit testing for an assignment. Just wondering if it's possible to have multiple assertEquals() statements in the same test? When it passes, does that mean that it will fail if one assertEquals statement fails? Or does it only take one assertEquals() statement?

        car3 = new Car("gargle", 45, false);
        car4 = new Car("cheese", 45, true);
        moto3 = new MotorCycle("ass", 45);
    
        assertEquals(true, carPark.spacesAvailable(car3));
        assertEquals(true, carPark.spacesAvailable(car4));
        assertEquals(true, carPark.spacesAvailable(moto3));
    

    Will only the first assertEquals be used or will all be used