A method needs to be tested for multiple scenarios, multiple scenarios will have multiple test case methods, we may require to test a particular type of scenario only not the entire test suit.
for this, JUnit 5 provides @Tag
annotation to structure them accordingly. we can tag multiple test cases or test classes.
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;
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'
}
}
gradle clean test
or
./gradlew clean test