Junit 5 @Tag Specific Gradle Task

Junit5 provides us @Tag annotation to differentiate test cases based on the scenario. The gradle task runs the specific @Tag method defined in the test task.
but in a production environment or CICD enable environment it is not possible to edit build.gradle file multiple times.
a better approach is to create a separate gradle task, specific to each @Tag.

package org.wesome.junit5;

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

    public int subApple(int apple1, int apple2) {
        return apple1 - apple2;
    }
}
package org.wesome.junit5;

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

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

public class AppleCalculatorTest {

    @Test
    @Tag("add")
    void addAppleTestCase1() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals(2, appleCalculator.addApple(1, 1), "1 apple + 1 apple is 2 apple");
    }

    @Test
    @Tag("add")
    void addAppleTestCase2() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals(2, appleCalculator.addApple(1, 1), "1 apple + 1 apple is 2 apple");
    }

    @Test
    @Tag("sub")
    void subAppleTestCase1() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals(1, appleCalculator.subApple(2, 1), "2 apple - 1 apple is 1 apple");
    }

    @Test
    @Tag("sub")
    void subAppleTestCase2() {
        AppleCalculator appleCalculator = new AppleCalculator();
        assertEquals(1, appleCalculator.subApple(2, 1), "2 apple - 1 apple is 1 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

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

test {
    testLogging {
        events "started", "passed", "skipped", "failed"
    }
    useJUnitPlatform {
        includeTags 'add'
        excludeTags 'sub'
    }
}

tasks.register("addTests", Test) {
    testLogging {
        events "started", "passed", "skipped", "failed"
    }
    useJUnitPlatform {
        includeTags 'add'
    }
    mustRunAfter check
}

tasks.register("subTests", Test) {
    testLogging {
        events "started", "passed", "skipped", "failed"
    }
    useJUnitPlatform {
        includeTags 'sub'
    }
    mustRunAfter check
}

to run addTests gradle task

gradle clean addTests
or
./gradlew clean addTests

to run subTests gradle task

gradle clean subTests
or
./gradlew clean subTests

follow us on