Junit 5 Test Class Lifecycle @BeforeAll Super Class

we might come across a scenario where we have multiple test case class and we need to execute some code every time before running different test case class. 1 way to write @BeforeAll 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.BeforeAll;

public class AppleCalculatorTestSuperClass {
    @BeforeAll
    public static void beforeAll() {
        System.out.println("AppleCalculatorTest.beforeAll");
    }
}
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