Junit 5 Test Class Lifecycle @BeforeEach 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 each test case class. 1 way to write @BeforeEach in 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 {
    @BeforeEach
    public 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 addApple() {
        System.out.println("AddAppleCalculatorTest.addApple");
        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 subApple() {
        System.out.println("SubAppleCalculatorTest.subApple");
        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 @BeforeEach annotation will run as per inheritance.

follow us on