Split or move testing-modules/junit-5 module (#7879)
This commit is contained in:
committed by
Josh Cummings
parent
2e030a63b7
commit
160fd28fdd
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.junit5.registerextension;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.api.extension.TestInstancePostProcessor;
|
||||
|
||||
public class LoggingExtension implements TestInstancePostProcessor {
|
||||
|
||||
@Override
|
||||
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
|
||||
Logger logger = LogManager.getLogger(testInstance.getClass());
|
||||
testInstance.getClass()
|
||||
.getMethod("setLogger", Logger.class)
|
||||
.invoke(testInstance, logger);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.junit5.registerextension;
|
||||
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeEachCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* This extension is meant to demonstrate the use of RegisterExtension.
|
||||
*/
|
||||
public class RegisterExtensionSampleExtension implements BeforeAllCallback, BeforeEachCallback {
|
||||
|
||||
private final String type;
|
||||
Logger logger = LoggerFactory.getLogger(RegisterExtensionSampleExtension.class);
|
||||
|
||||
public RegisterExtensionSampleExtension(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeAll(ExtensionContext extensionContext) throws Exception {
|
||||
logger.info("Type {} In beforeAll : {}", type, extensionContext.getDisplayName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeEach(ExtensionContext extensionContext) throws Exception {
|
||||
logger.info("Type {} In beforeEach : {}", type, extensionContext.getDisplayName());
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.junit5;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
import org.junit.jupiter.api.RepetitionInfo;
|
||||
import org.junit.jupiter.api.TestInfo;
|
||||
|
||||
public class RepeatedTestAnnotationUnitTest {
|
||||
|
||||
@BeforeEach
|
||||
void beforeEachTest() {
|
||||
System.out.println("Before Each Test");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void afterEachTest() {
|
||||
System.out.println("After Each Test");
|
||||
System.out.println("=====================");
|
||||
}
|
||||
|
||||
@RepeatedTest(3)
|
||||
void repeatedTest(TestInfo testInfo) {
|
||||
System.out.println("Executing repeated test");
|
||||
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
|
||||
}
|
||||
|
||||
@RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME)
|
||||
void repeatedTestWithLongName() {
|
||||
System.out.println("Executing repeated test with long name");
|
||||
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
|
||||
}
|
||||
|
||||
@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
|
||||
void repeatedTestWithShortName() {
|
||||
System.out.println("Executing repeated test with long name");
|
||||
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
|
||||
}
|
||||
|
||||
@RepeatedTest(value = 3, name = "Custom name {currentRepetition}/{totalRepetitions}")
|
||||
void repeatedTestWithCustomDisplayName() {
|
||||
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
|
||||
}
|
||||
|
||||
@RepeatedTest(3)
|
||||
void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) {
|
||||
System.out.println("Repetition #" + repetitionInfo.getCurrentRepetition());
|
||||
assertEquals(3, repetitionInfo.getTotalRepetitions());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.baeldung.junit5.conditional;
|
||||
|
||||
import org.junit.jupiter.api.RepeatedTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.*;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
public class ConditionalAnnotationsUnitTest {
|
||||
@Test
|
||||
@EnabledOnOs({OS.WINDOWS, OS.MAC})
|
||||
public void shouldRunBothWindowsAndMac() {
|
||||
System.out.println("runs on Windows and Mac");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledOnOs(OS.LINUX)
|
||||
public void shouldNotRunAtLinux() {
|
||||
System.out.println("will not run on Linux");
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledOnJre({JRE.JAVA_10, JRE.JAVA_11})
|
||||
public void shouldOnlyRunOnJava10And11() {
|
||||
System.out.println("runs with java 10 and 11");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledOnJre(JRE.OTHER)
|
||||
public void thisTestOnlyRunsWithUpToDateJREs() {
|
||||
System.out.println("this test will only run on java8, 9, 10 and 11.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledIfSystemProperty(named = "java.vm.vendor", matches = "Oracle.*")
|
||||
public void onlyIfVendorNameStartsWithOracle() {
|
||||
System.out.println("runs only if vendor name starts with Oracle");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIfSystemProperty(named = "file.separator", matches = "[/]")
|
||||
public void disabledIfFileSeperatorIsSlash() {
|
||||
System.out.println("Will not run if file.sepeartor property is /");
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledIfEnvironmentVariable(named = "GDMSESSION", matches = "ubuntu")
|
||||
public void onlyRunOnUbuntuServer() {
|
||||
System.out.println("only runs if GDMSESSION is ubuntu");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIfEnvironmentVariable(named = "LC_TIME", matches = ".*UTF-8.")
|
||||
public void shouldNotRunWhenTimeIsNotUTF8() {
|
||||
System.out.println("will not run if environment variable LC_TIME is UTF-8");
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledIf("'FR' == systemProperty.get('user.country')")
|
||||
public void onlyFrenchPeopleWillRunThisMethod() {
|
||||
System.out.println("will run only if user.country is FR");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIf("java.lang.System.getProperty('os.name').toLowerCase().contains('mac')")
|
||||
public void shouldNotRunOnMacOS() {
|
||||
System.out.println("will not run if our os.name is mac");
|
||||
}
|
||||
|
||||
@Test
|
||||
@EnabledIf(value = {
|
||||
"load('nashorn:mozilla_compat.js')",
|
||||
"importPackage(java.time)",
|
||||
"",
|
||||
"var thisMonth = LocalDate.now().getMonth().name()",
|
||||
"var february = Month.FEBRUARY.name()",
|
||||
"thisMonth.equals(february)"
|
||||
},
|
||||
engine = "nashorn",
|
||||
reason = "Self-fulfilling: {result}")
|
||||
public void onlyRunsInFebruary() {
|
||||
System.out.println("this test only runs in February");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisabledIf("systemEnvironment.get('XPC_SERVICE_NAME') != null " +
|
||||
"&& systemEnvironment.get('XPC_SERVICE_NAME').contains('intellij')")
|
||||
public void notValidForIntelliJ() {
|
||||
System.out.println("this test will run if our ide is INTELLIJ");
|
||||
}
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Test
|
||||
@DisabledOnOs({OS.WINDOWS, OS.SOLARIS, OS.OTHER})
|
||||
@EnabledOnJre({JRE.JAVA_9, JRE.JAVA_10, JRE.JAVA_11})
|
||||
@interface ThisTestWillOnlyRunAtLinuxAndMacWithJava9Or10Or11 {
|
||||
}
|
||||
|
||||
@ThisTestWillOnlyRunAtLinuxAndMacWithJava9Or10Or11
|
||||
public void someSuperTestMethodHere() {
|
||||
System.out.println("this method will run with java9, 10, 11 and Linux or macOS.");
|
||||
}
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@DisabledIf("Math.random() >= 0.5")
|
||||
@interface CoinToss {
|
||||
}
|
||||
|
||||
@RepeatedTest(2)
|
||||
@CoinToss
|
||||
public void gamble() {
|
||||
System.out.println("This tests run status is a gamble with %50 rate");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.ArgumentsProvider;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
class BlankStringsArgumentsProvider implements ArgumentsProvider {
|
||||
|
||||
@Override
|
||||
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
|
||||
return Stream.of(
|
||||
Arguments.of((String) null),
|
||||
Arguments.of(""),
|
||||
Arguments.of(" ")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.time.Month;
|
||||
import java.util.EnumSet;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class EnumsUnitTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(Month.class)
|
||||
void getValueForAMonth_IsAlwaysBetweenOneAndTwelve(Month month) {
|
||||
int monthNumber = month.getValue();
|
||||
assertTrue(monthNumber >= 1 && monthNumber <= 12);
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{index} {0} is 30 days long")
|
||||
@EnumSource(value = Month.class, names = {"APRIL", "JUNE", "SEPTEMBER", "NOVEMBER"})
|
||||
void someMonths_Are30DaysLong(Month month) {
|
||||
final boolean isALeapYear = false;
|
||||
assertEquals(30, month.length(isALeapYear));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = Month.class, names = {"APRIL", "JUNE", "SEPTEMBER", "NOVEMBER", "FEBRUARY"}, mode = EnumSource.Mode.EXCLUDE)
|
||||
void exceptFourMonths_OthersAre31DaysLong(Month month) {
|
||||
final boolean isALeapYear = false;
|
||||
assertEquals(31, month.length(isALeapYear));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = Month.class, names = ".+BER", mode = EnumSource.Mode.MATCH_ANY)
|
||||
void fourMonths_AreEndingWithBer(Month month) {
|
||||
EnumSet<Month> months = EnumSet.of(Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER, Month.DECEMBER);
|
||||
assertTrue(months.contains(month));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"APRIL", "JUNE", "SEPTEMBER", "NOVEMBER"})
|
||||
void someMonths_Are30DaysLongCsv(Month month) {
|
||||
final boolean isALeapYear = false;
|
||||
assertEquals(30, month.length(isALeapYear));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.converter.ConvertWith;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class LocalDateUnitTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"2018/12/25,2018", "2019/02/11,2019"})
|
||||
void getYear_ShouldWorkAsExpected(@ConvertWith(SlashyDateConverter.class) LocalDate date, int expected) {
|
||||
assertEquals(expected, date.getYear());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
public class Numbers {
|
||||
|
||||
public static boolean isOdd(int number) {
|
||||
return number % 2 != 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class NumbersUnitTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE})
|
||||
void isOdd_ShouldReturnTrueForOddNumbers(int number) {
|
||||
assertTrue(Numbers.isOdd(number));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
class Person {
|
||||
|
||||
private final String firstName;
|
||||
private final String middleName;
|
||||
private final String lastName;
|
||||
|
||||
public Person(String firstName, String middleName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.middleName = middleName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String fullName() {
|
||||
if (middleName == null || middleName.trim().isEmpty()) return String.format("%s %s", firstName, lastName);
|
||||
|
||||
return String.format("%s %s %s", firstName, middleName, lastName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.api.extension.ParameterContext;
|
||||
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
|
||||
import org.junit.jupiter.params.aggregator.ArgumentsAggregationException;
|
||||
import org.junit.jupiter.params.aggregator.ArgumentsAggregator;
|
||||
|
||||
class PersonAggregator implements ArgumentsAggregator {
|
||||
|
||||
@Override
|
||||
public Object aggregateArguments(ArgumentsAccessor accessor, ParameterContext context)
|
||||
throws ArgumentsAggregationException {
|
||||
return new Person(accessor.getString(1), accessor.getString(2), accessor.getString(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.aggregator.AggregateWith;
|
||||
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class PersonUnitTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"Isaac,,Newton, Isaac Newton", "Charles,Robert,Darwin,Charles Robert Darwin"})
|
||||
void fullName_ShouldGenerateTheExpectedFullName(ArgumentsAccessor argumentsAccessor) {
|
||||
String firstName = argumentsAccessor.getString(0);
|
||||
String middleName = (String) argumentsAccessor.get(1);
|
||||
String lastName = argumentsAccessor.get(2, String.class);
|
||||
String expectedFullName = argumentsAccessor.getString(3);
|
||||
|
||||
Person person = new Person(firstName, middleName, lastName);
|
||||
assertEquals(expectedFullName, person.fullName());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"Isaac Newton,Isaac,,Newton", "Charles Robert Darwin,Charles,Robert,Darwin"})
|
||||
void fullName_ShouldGenerateTheExpectedFullName(String expectedFullName,
|
||||
@AggregateWith(PersonAggregator.class) Person person) {
|
||||
|
||||
assertEquals(expectedFullName, person.fullName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.api.extension.ParameterContext;
|
||||
import org.junit.jupiter.params.converter.ArgumentConversionException;
|
||||
import org.junit.jupiter.params.converter.ArgumentConverter;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
class SlashyDateConverter implements ArgumentConverter {
|
||||
|
||||
@Override
|
||||
public Object convert(Object source, ParameterContext context) throws ArgumentConversionException {
|
||||
if (!(source instanceof String))
|
||||
throw new IllegalArgumentException("The argument should be a string: " + source);
|
||||
|
||||
try {
|
||||
String[] parts = ((String) source).split("/");
|
||||
int year = Integer.parseInt(parts[0]);
|
||||
int month = Integer.parseInt(parts[1]);
|
||||
int day = Integer.parseInt(parts[2]);
|
||||
|
||||
return LocalDate.of(year, month, day);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("Failed to convert", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StringParams {
|
||||
|
||||
static Stream<String> blankStrings() {
|
||||
return Stream.of(null, "", " ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
class Strings {
|
||||
|
||||
static boolean isBlank(String input) {
|
||||
return input == null || input.trim().isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class StringsUnitTest {
|
||||
|
||||
static Stream<Arguments> arguments = Stream.of(
|
||||
Arguments.of(null, true), // null strings should be considered blank
|
||||
Arguments.of("", true),
|
||||
Arguments.of(" ", true),
|
||||
Arguments.of("not blank", false)
|
||||
);
|
||||
|
||||
@ParameterizedTest
|
||||
@VariableSource("arguments")
|
||||
void isBlank_ShouldReturnTrueForNullOrBlankStringsVariableSource(String input, boolean expected) {
|
||||
assertEquals(expected, Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " "})
|
||||
void isBlank_ShouldReturnTrueForNullOrBlankStrings(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("provideStringsForIsBlank")
|
||||
void isBlank_ShouldReturnTrueForNullOrBlankStrings(String input, boolean expected) {
|
||||
assertEquals(expected, Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource // Please note method name is not provided
|
||||
void isBlank_ShouldReturnTrueForNullOrBlankStringsOneArgument(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("com.baeldung.junit5.parameterized.StringParams#blankStrings")
|
||||
void isBlank_ShouldReturnTrueForNullOrBlankStringsExternalSource(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ArgumentsSource(BlankStringsArgumentsProvider.class)
|
||||
void isBlank_ShouldReturnTrueForNullOrBlankStringsArgProvider(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
private static Stream<String> isBlank_ShouldReturnTrueForNullOrBlankStringsOneArgument() {
|
||||
return Stream.of(null, "", " ");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("provideStringsForIsBlankList")
|
||||
void isBlank_ShouldReturnTrueForNullOrBlankStringsList(String input, boolean expected) {
|
||||
assertEquals(expected, Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"test,TEST", "tEst,TEST", "Java,JAVA"}) // Passing a CSV pair per test execution
|
||||
void toUpperCase_ShouldGenerateTheExpectedUppercaseValue(String input, String expected) {
|
||||
String actualValue = input.toUpperCase();
|
||||
assertEquals(expected, actualValue);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(value = {"test:test", "tEst:test", "Java:java"}, delimiter =':') // Using : as the column separator.
|
||||
void toLowerCase_ShouldGenerateTheExpectedLowercaseValue(String input, String expected) {
|
||||
String actualValue = input.toLowerCase();
|
||||
assertEquals(expected, actualValue);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvFileSource(resources = "/data.csv", numLinesToSkip = 1)
|
||||
void toUpperCase_ShouldGenerateTheExpectedUppercaseValueCSVFile(String input, String expected) {
|
||||
String actualValue = input.toUpperCase();
|
||||
assertEquals(expected, actualValue);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullSource
|
||||
void isBlank_ShouldReturnTrueForNullInputs(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EmptySource
|
||||
void isBlank_ShouldReturnTrueForEmptyStrings(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
void isBlank_ShouldReturnTrueForNullAndEmptyStrings(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" ", "\t", "\n"})
|
||||
void isBlank_ShouldReturnTrueForAllTypesOfBlankStrings(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> provideStringsForIsBlank() {
|
||||
return Stream.of(
|
||||
Arguments.of(null, true), // null strings should be considered blank
|
||||
Arguments.of("", true),
|
||||
Arguments.of(" ", true),
|
||||
Arguments.of("not blank", false)
|
||||
);
|
||||
}
|
||||
|
||||
private static List<Arguments> provideStringsForIsBlankList() {
|
||||
return Arrays.asList(
|
||||
Arguments.of(null, true), // null strings should be considered blank
|
||||
Arguments.of("", true),
|
||||
Arguments.of(" ", true),
|
||||
Arguments.of("not blank", false)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.ArgumentsProvider;
|
||||
import org.junit.jupiter.params.support.AnnotationConsumer;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
class VariableArgumentsProvider implements ArgumentsProvider, AnnotationConsumer<VariableSource> {
|
||||
|
||||
private String variableName;
|
||||
|
||||
@Override
|
||||
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
|
||||
return context.getTestClass()
|
||||
.map(this::getField)
|
||||
.map(this::getValue)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Failed to load test arguments"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(VariableSource variableSource) {
|
||||
variableName = variableSource.value();
|
||||
}
|
||||
|
||||
private Field getField(Class<?> clazz) {
|
||||
try {
|
||||
return clazz.getDeclaredField(variableName);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Stream<Arguments> getValue(Field field) {
|
||||
Object value = null;
|
||||
try {
|
||||
value = field.get(null);
|
||||
} catch (Exception ignored) {}
|
||||
|
||||
return value == null ? null : (Stream<Arguments>) value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.junit5.parameterized;
|
||||
|
||||
import org.junit.jupiter.params.provider.ArgumentsSource;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
@Documented
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@ArgumentsSource(VariableArgumentsProvider.class)
|
||||
public @interface VariableSource {
|
||||
|
||||
/**
|
||||
* Represents the name of the static variable to load the test arguments from.
|
||||
*
|
||||
* @return Static variable name.
|
||||
*/
|
||||
String value();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.junit5.registerextension;
|
||||
|
||||
import com.baeldung.junit5.registerextension.RegisterExtensionSampleExtension;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
/**
|
||||
* This test demonstrates the use of the same extension in two ways.
|
||||
* 1. Once as instance level field: Only method level callbacks are called.
|
||||
* 2. Once as class level static field: All methods are called.
|
||||
*/
|
||||
public class RegisterExtensionUnitTest {
|
||||
|
||||
@RegisterExtension
|
||||
static RegisterExtensionSampleExtension staticExtension = new RegisterExtensionSampleExtension("static version");
|
||||
|
||||
@RegisterExtension
|
||||
RegisterExtensionSampleExtension instanceLevelExtension = new RegisterExtensionSampleExtension("instance version");
|
||||
|
||||
@Test
|
||||
public void demoTest() {
|
||||
Assertions.assertEquals("instance version", instanceLevelExtension.getType());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
input,expected
|
||||
test,TEST
|
||||
tEst,TEST
|
||||
Java,JAVA
|
||||
|
Reference in New Issue
Block a user