Junit 5 Test Class Lifecycle @AfterAll Super Class

we might come across a scenario where we have multiple test case class and we need to execute some code every time after running different test case class. 1 way to write @AfterAll on all test case class or the better way is to create a superclass and extend this in all test case base class.

package com.example.junit5.sujan;

public class AppleCalculator {
    public int addApple(int apple1, int apple2) {
        return apple1 + apple2;
    }

    public int subApple(int apple1, int apple2) {
        return apple1 - apple2;
    }
}
package com.example.junit5.sujan;

import org.junit.jupiter.api.AfterAll;

public class AppleCalculatorTestSuperClass {
    @AfterAll
    public static void afterAll() {
        System.out.println("AppleCalculatorTest.afterAll");
    }
}
package com.example.junit5.sujan;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class AddAppleCalculatorTest extends AppleCalculatorTestSuperClass {

    @Test
    void test() {
        System.out.println("AppleCalculatorTest.test");
        AppleCalculator appleCalculator = new AppleCalculator();
        Assertions.assertEquals(2, appleCalculator.addApple(1, 1));
    }
}
package com.example.junit5.sujan;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class SubAppleCalculatorTest extends AppleCalculatorTestSuperClass {

    @Test
    void test() {
        System.out.println("AppleCalculatorTest.test");
        AppleCalculator appleCalculator = new AppleCalculator();
        Assertions.assertEquals(1, appleCalculator.subApple(2, 1));
    }
}
plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}

 

Super Class methods declared with @BeforeAll annotation will run as per inheritance.

follow us on