Split or move testing-modules/junit-5 module (#7879)

This commit is contained in:
Catalin Burcea
2019-10-03 06:33:18 +03:00
committed by Josh Cummings
parent 2e030a63b7
commit 160fd28fdd
44 changed files with 176 additions and 46 deletions

View File

@@ -1,15 +0,0 @@
package com.baeldung.junit5vstestng;
public class Calculator {
public double divide(double a, double b) {
if (b == 0) {
throw new DivideByZeroException("Divider cannot be equal to zero!");
}
return a/b;
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.junit5vstestng;
public class DivideByZeroException extends RuntimeException {
public DivideByZeroException(String message) {
super(message);
}
}

View File

@@ -1,192 +0,0 @@
package com.baeldung;
import static java.time.Duration.ofSeconds;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeout;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Unit test that demonstrate the different assertions available within JUnit 4
*/
@DisplayName("Test case for assertions")
public class AssertionUnitTest {
@Test
@DisplayName("Arrays should be equals")
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = {'J', 'u', 'p', 'i', 't', 'e', 'r'};
char[] actual = "Jupiter".toCharArray();
assertArrayEquals(expected, actual, "Arrays should be equal");
}
@Test
@DisplayName("The area of two polygons should be equal")
public void whenAssertingEquality_thenEqual() {
float square = 2 * 2;
float rectangle = 2 * 2;
assertEquals(square, rectangle);
}
@Test
public void whenAssertingEqualityWithDelta_thenEqual() {
float square = 2 * 2;
float rectangle = 3 * 2;
float delta = 2;
assertEquals(square, rectangle, delta);
}
@Test
public void whenAssertingConditions_thenVerified() {
assertTrue(5 > 4, "5 is greater the 4");
assertTrue(null == null, "null is equal to null");
}
@Test
public void whenAssertingNull_thenTrue() {
Object cat = null;
assertNull(cat, () -> "The cat should be null");
}
@Test
public void whenAssertingNotNull_thenTrue() {
Object dog = new Object();
assertNotNull(dog, () -> "The dog should not be null");
}
@Test
public void whenAssertingSameObject_thenSuccessfull() {
String language = "Java";
Optional<String> optional = Optional.of(language);
assertSame(language, optional.get());
}
@Test
public void givenBooleanSupplier_whenAssertingCondition_thenVerified() {
BooleanSupplier condition = () -> 5 > 6;
assertFalse(condition, "5 is not greater then 6");
}
@Test
@Disabled
public void whenFailingATest_thenFailed() {
// Test not completed
fail("FAIL - test not completed");
}
@Test
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
Object obj = null;
assertAll(
"heading",
() -> assertEquals(4, 2 * 2, "4 is 2 times 2"),
() -> assertEquals("java", "JAVA".toLowerCase()),
() -> assertEquals(obj, null, "null is equal to null")
);
}
@Test
public void givenTwoLists_whenAssertingIterables_thenEquals() {
Iterable<String> al = new ArrayList<>(asList("Java", "Junit", "Test"));
Iterable<String> ll = new LinkedList<>(asList("Java", "Junit", "Test"));
assertIterableEquals(al, ll);
}
@Test
public void whenAssertingTimeout_thenNotExceeded() {
assertTimeout(
ofSeconds(2),
() -> {
// code that requires less then 2 minutes to execute
Thread.sleep(1000);
}
);
}
@Test
public void whenAssertingTimeoutPreemptively_thenNotExceeded() {
assertTimeoutPreemptively(
ofSeconds(2),
() -> {
// code that requires less then 2 minutes to execute
Thread.sleep(1000);
}
);
}
@Test
public void whenAssertingEquality_thenNotEqual() {
Integer value = 5; // result of an algorithm
assertNotEquals(0, value, "The result cannot be 0");
}
@Test
public void whenAssertingEqualityListOfStrings_thenEqual() {
List<String> expected = asList("Java", "\\d+", "JUnit");
List<String> actual = asList("Java", "11", "JUnit");
assertLinesMatch(expected, actual);
}
@Test
void whenAssertingException_thenThrown() {
Throwable exception = assertThrows(
IllegalArgumentException.class,
() -> {
throw new IllegalArgumentException("Exception message");
}
);
assertEquals("Exception message", exception.getMessage());
}
@Test
public void testConvertToDoubleThrowException() {
String age = "eighteen";
assertThrows(NumberFormatException.class, () -> {
convertToInt(age);
});
assertThrows(NumberFormatException.class, () -> {
convertToInt(age);
});
}
private static Integer convertToInt(String str) {
if (str == null) {
return null;
}
return Integer.valueOf(str);
}
}

View File

@@ -1,27 +0,0 @@
package com.baeldung;
import com.baeldung.extensions.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());
}
}

View File

@@ -1,52 +0,0 @@
package com.baeldung;
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 RepeatedTestExample {
@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());
}
}

View File

@@ -1,119 +0,0 @@
package com.baeldung.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");
}
}

View File

@@ -1,4 +1,4 @@
package com.baeldung;
package com.baeldung.dynamictests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -17,10 +17,8 @@ import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.ThrowingConsumer;
import com.baeldung.helpers.Employee;
import com.baeldung.helpers.EmployeeDao;
public class DynamicTestsExample {
public class DynamicTestsUnitTest {
@TestFactory
Collection<DynamicTest> dynamicTestsWithCollection() {

View File

@@ -0,0 +1,38 @@
package com.baeldung.dynamictests;
public class Employee {
private long id;
private String firstName;
public Employee(long id) {
this.id = id;
this.firstName = "";
}
public Employee(long id, String firstName) {
this.id = id;
this.firstName = firstName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + "]";
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.dynamictests;
public class EmployeeDao {
public Employee save(long id) {
return new Employee(id);
}
public Employee save(long id, String firstName) {
return new Employee(id, firstName);
}
public Employee update(Employee employee) {
return employee;
}
}

View File

@@ -1,34 +0,0 @@
package com.baeldung.extensions;
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;
}
}

View File

@@ -1,22 +0,0 @@
package com.baeldung.junit4vstestng;
import static org.junit.Assert.assertTrue;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SortedUnitTest {
@Test
public void a_givenString_whenChangedtoInt_thenTrue() {
assertTrue(Integer.valueOf("10") instanceof Integer);
}
@Test
public void b_givenInt_whenChangedtoString_thenTrue() {
assertTrue(String.valueOf(10) instanceof String);
}
}

View File

@@ -1,58 +0,0 @@
package com.baeldung.junit4vstestng;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class SummationServiceIntegrationTest {
private static List<Integer> numbers;
@BeforeClass
public static void initialize() {
numbers = new ArrayList<>();
}
@AfterClass
public static void tearDown() {
numbers = null;
}
@Before
public void runBeforeEachTest() {
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@After
public void runAfterEachTest() {
numbers.clear();
}
@Test
public void givenNumbers_sumEquals_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Ignore
@Test
public void givenEmptyList_sumEqualsZero_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Test(expected = ArithmeticException.class)
public void givenNumber_whenThrowsException_thenCorrect() {
int i = 1 / 0;
}
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.junit5vstestng;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class CalculatorUnitTest {
@Test
public void whenDividerIsZero_thenDivideByZeroExceptionIsThrown() {
Calculator calculator = new Calculator();
assertThrows(DivideByZeroException.class,
() -> calculator.divide(10, 0));
}
}

View File

@@ -1,15 +0,0 @@
package com.baeldung.junit5vstestng;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
public class Class1UnitTest {
@Test
public void testCase_InClass1UnitTest() {
assertTrue(true);
}
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.junit5vstestng;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
public class Class2UnitTest {
@Test
public void testCase_InClass2UnitTest() {
assertTrue(true);
}
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.junit5vstestng;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class CustomNameUnitTest {
@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
@DisplayName("Test Method to check that the inputs are not nullable")
void givenString_TestNullOrNot(String word) {
assertNotNull(word);
}
}

View File

@@ -1,45 +0,0 @@
package com.baeldung.junit5vstestng;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.EnumSet;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
public class ParameterizedUnitTest {
@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
void givenString_TestNullOrNot(String word) {
assertNotNull(word);
}
@ParameterizedTest
@EnumSource(value = PizzaDeliveryStrategy.class, names = {"EXPRESS", "NORMAL"})
void givenEnum_TestContainsOrNot(PizzaDeliveryStrategy timeUnit) {
assertTrue(EnumSet.of(PizzaDeliveryStrategy.EXPRESS, PizzaDeliveryStrategy.NORMAL).contains(timeUnit));
}
@ParameterizedTest
@MethodSource("wordDataProvider")
void givenMethodSource_TestInputStream(String argument) {
assertNotNull(argument);
}
static Stream<String> wordDataProvider() {
return Stream.of("foo", "bar");
}
@ParameterizedTest
@CsvSource({ "1, Car", "2, House", "3, Train" })
void givenCSVSource_TestContent(int id, String word) {
assertNotNull(id);
assertNotNull(word);
}
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.junit5vstestng;
public enum PizzaDeliveryStrategy {
EXPRESS,
NORMAL;
}

View File

@@ -1,11 +0,0 @@
package com.baeldung.junit5vstestng;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@SelectClasses({Class1UnitTest.class, Class2UnitTest.class})
public class SelectClassesSuiteUnitTest {
}

View File

@@ -1,11 +0,0 @@
package com.baeldung.junit5vstestng;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@SelectPackages({ "org.baeldung.java.suite.childpackage1", "org.baeldung.java.suite.childpackage2" })
public class SelectPackagesSuiteUnitTest {
}

View File

@@ -1,53 +0,0 @@
package com.baeldung.junit5vstestng;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SummationServiceUnitTest {
private static List<Integer> numbers;
@BeforeAll
public static void initialize() {
numbers = new ArrayList<>();
}
@AfterAll
public static void tearDown() {
numbers = null;
}
@BeforeEach
public void runBeforeEachTest() {
numbers.add(1);
numbers.add(2);
numbers.add(3);
}
@AfterEach
public void runAfterEachTest() {
numbers.clear();
}
@Test
public void givenNumbers_sumEquals_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
@Ignore
@Test
public void givenEmptyList_sumEqualsZero_thenCorrect() {
int sum = numbers.stream()
.reduce(0, Integer::sum);
Assert.assertEquals(6, sum);
}
}

View File

@@ -1,19 +0,0 @@
package com.baeldung.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(" ")
);
}
}

View File

@@ -1,50 +0,0 @@
package com.baeldung.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));
}
}

View File

@@ -1,18 +0,0 @@
package com.baeldung.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());
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.parameterized;
public class Numbers {
public static boolean isOdd(int number) {
return number % 2 != 0;
}
}

View File

@@ -1,15 +0,0 @@
package com.baeldung.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));
}
}

View File

@@ -1,20 +0,0 @@
package com.baeldung.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);
}
}

View File

@@ -1,15 +0,0 @@
package com.baeldung.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));
}
}

View File

@@ -1,31 +0,0 @@
package com.baeldung.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());
}
}

View File

@@ -1,27 +0,0 @@
package com.baeldung.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);
}
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.parameterized;
import java.util.stream.Stream;
public class StringParams {
static Stream<String> blankStrings() {
return Stream.of(null, "", " ");
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.parameterized;
class Strings {
static boolean isBlank(String input) {
return input == null || input.trim().isEmpty();
}
}

View File

@@ -1,131 +0,0 @@
package com.baeldung.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.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)
);
}
}

View File

@@ -1,45 +0,0 @@
package com.baeldung.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;
}
}

View File

@@ -1,19 +0,0 @@
package com.baeldung.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();
}

View File

@@ -1,4 +0,0 @@
input,expected
test,TEST
tEst,TEST
Java,JAVA
1 input expected
2 test TEST
3 tEst TEST
4 Java JAVA