Junit 5 Difference between Assert and AssertAll

Junit 5 provides assert and assertAll, both methods are used to validate expected output vs actual output, but there is a difference between both the assert methods.

in the assert method, if the first assert fails, JUnit fails the test case that instant and doesn't validate the rest of asserts, whereas, in assertAll, it validates all methods, even if some asserts fails then also it will continue test rest of the assert and give validation result for all failed asserts.

package org.wesome.junit5;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

public class AppleCalculator {
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Apple {
        private int appleId;
        private String appleName;

    }

    public Apple addApple(int appleId, String appleName) {
        Apple apple = new Apple(appleId, appleName);
        return apple;
    }
}
package org.wesome.junit5;

import org.junit.jupiter.api.Test;
import org.wesome.dsalgo.AppleCalculator.Apple;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class AppleCalculatorTest {
    @Test
    void addAppleAssertTest() {
        System.out.println("AppleCalculatorTest.addAppleTest");
        AppleCalculator appleCalculator = new AppleCalculator();
        Apple apple = appleCalculator.addApple(1, "apple");
        assertNotNull(apple, "apple object should not be null");
        assertEquals(11, apple.getAppleId(), "appleId should be 1");
        assertEquals("apple1", apple.getAppleName(), "appleName should be apple");
    }

    @Test
    void addAppleAssertAllTest() {
        System.out.println("AppleCalculatorTest.addAppleTest");
        AppleCalculator appleCalculator = new AppleCalculator();
        Apple apple = appleCalculator.addApple(1, "apple");
        assertAll(() -> assertNotNull(apple, "apple object should not be null"),
                () -> assertEquals(11, apple.getAppleId(), "appleId should be 1"),
                () -> assertEquals("apple1", apple.getAppleName(), "appleName should be apple"));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

test {
    useJUnitPlatform()
}

follow us on