formatting work

This commit is contained in:
eugenp
2017-08-24 15:30:33 +03:00
parent 1cba1b043c
commit b00a9e61bc
36 changed files with 628 additions and 616 deletions
@@ -6,23 +6,23 @@ import org.junit.jupiter.api.Test;
public class AssertionUnitTest {
@Test
public void testConvertToDoubleThrowException() {
String age = "eighteen";
assertThrows(NumberFormatException.class, () -> {
convertToInt(age);
});
@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);
}
assertThrows(NumberFormatException.class, () -> {
convertToInt(age);
});
}
private static Integer convertToInt(String str) {
if (str == null) {
return null;
}
return Integer.valueOf(str);
}
}
@@ -24,9 +24,6 @@ public class AssumptionUnitTest {
@Test
void assumptionThat() {
String someString = "Just a string";
assumingThat(
someString.equals("Just a string"),
() -> assertEquals(2 + 2, 4)
);
assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4));
}
}
@@ -24,40 +24,33 @@ public class DynamicTestsExample {
@TestFactory
Collection<DynamicTest> dynamicTestsWithCollection() {
return Arrays.asList(
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
}
@TestFactory
Iterable<DynamicTest> dynamicTestsWithIterable() {
return Arrays.asList(
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
}
@TestFactory
Iterator<DynamicTest> dynamicTestsWithIterator() {
return Arrays.asList(
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
.iterator();
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
.iterator();
}
@TestFactory
Stream<DynamicTest> dynamicTestsFromIntStream() {
return IntStream.iterate(0, n -> n + 2).limit(10).mapToObj(
n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
return IntStream.iterate(0, n -> n + 2)
.limit(10)
.mapToObj(n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
}
@TestFactory
Stream<DynamicTest> dynamicTestsFromStream() {
// sample input and output
List<String> inputList =
Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
List<String> outputList =
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
List<String> outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
// input generator that generates inputs using inputList
Iterator<String> inputGenerator = inputList.iterator();
@@ -75,57 +68,56 @@ public class DynamicTestsExample {
// combine everything and return a Stream of DynamicTest
return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
}
@TestFactory
Stream<DynamicTest> dynamicTestsFromStreamInJava8() {
DomainNameResolver resolver = new DomainNameResolver();
List<String> inputList =
Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
List<String> outputList =
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
return inputList.stream().map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> {
int id = inputList.indexOf(dom);
assertEquals(outputList.get(id), resolver.resolveDomain(dom));
}));
List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
List<String> outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
return inputList.stream()
.map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> {
int id = inputList.indexOf(dom);
assertEquals(outputList.get(id), resolver.resolveDomain(dom));
}));
}
@TestFactory
Stream<DynamicTest> dynamicTestsForEmployeeWorkflows() {
List<Employee> inputList =
Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
List<Employee> inputList = Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
EmployeeDao dao = new EmployeeDao();
Stream<DynamicTest> saveEmployeeStream = inputList.stream().map(emp ->
DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
Employee returned = dao.save(emp.getId());
assertEquals(returned.getId(), emp.getId());
}));
Stream<DynamicTest> saveEmployeeWithFirstNameStream
= inputList.stream().filter(emp -> !emp.getFirstName().isEmpty())
Stream<DynamicTest> saveEmployeeStream = inputList.stream()
.map(emp -> DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
Employee returned = dao.save(emp.getId());
assertEquals(returned.getId(), emp.getId());
}));
Stream<DynamicTest> saveEmployeeWithFirstNameStream = inputList.stream()
.filter(emp -> !emp.getFirstName()
.isEmpty())
.map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> {
Employee returned = dao.save(emp.getId(), emp.getFirstName());
assertEquals(returned.getId(), emp.getId());
assertEquals(returned.getFirstName(), emp.getFirstName());
}));
Employee returned = dao.save(emp.getId(), emp.getFirstName());
assertEquals(returned.getId(), emp.getId());
assertEquals(returned.getFirstName(), emp.getFirstName());
}));
return Stream.concat(saveEmployeeStream, saveEmployeeWithFirstNameStream);
}
class DomainNameResolver {
private Map<String, String> ipByDomainName = new HashMap<>();
DomainNameResolver() {
this.ipByDomainName.put("www.somedomain.com", "154.174.10.56");
this.ipByDomainName.put("www.anotherdomain.com", "211.152.104.132");
this.ipByDomainName.put("www.yetanotherdomain.com", "178.144.120.156");
}
public String resolveDomain(String domainName) {
return ipByDomainName.get(domainName);
}
@@ -33,12 +33,14 @@ public class EmployeesTest {
public void whenAddEmployee_thenGetEmployee() throws SQLException {
Employee emp = new Employee(1, "john");
employeeDao.add(emp);
assertEquals(1, employeeDao.findAll().size());
assertEquals(1, employeeDao.findAll()
.size());
}
@Test
public void whenGetEmployees_thenEmptyList() throws SQLException {
assertEquals(0, employeeDao.findAll().size());
assertEquals(0, employeeDao.findAll()
.size());
}
public void setLogger(Logger logger) {
@@ -7,19 +7,19 @@ import org.junit.jupiter.api.Test;
public class ExceptionUnitTest {
@Test
void shouldThrowException() {
Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
throw new UnsupportedOperationException("Not supported");
});
assertEquals(exception.getMessage(), "Not supported");
}
@Test
void shouldThrowException() {
Throwable exception = assertThrows(UnsupportedOperationException.class, () -> {
throw new UnsupportedOperationException("Not supported");
});
assertEquals(exception.getMessage(), "Not supported");
}
@Test
void assertThrowsException() {
String str = null;
assertThrows(IllegalArgumentException.class, () -> {
Integer.valueOf(str);
});
}
@Test
void assertThrowsException() {
String str = null;
assertThrows(IllegalArgumentException.class, () -> {
Integer.valueOf(str);
});
}
}
@@ -13,21 +13,16 @@ class FirstUnitTest {
@Test
void lambdaExpressions() {
List<Integer> numbers = Arrays.asList(1, 2, 3);
assertTrue(numbers
.stream()
.mapToInt(i -> i)
.sum() > 5, "Sum should be greater than 5");
assertTrue(numbers.stream()
.mapToInt(i -> i)
.sum() > 5, "Sum should be greater than 5");
}
@Disabled("test to show MultipleFailuresError")
@Test
void groupAssertions() {
int[] numbers = {0, 1, 2, 3, 4};
assertAll("numbers",
() -> assertEquals(numbers[0], 1),
() -> assertEquals(numbers[3], 3),
() -> assertEquals(numbers[4], 1)
);
int[] numbers = { 0, 1, 2, 3, 4 };
assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1));
}
@Test
@@ -13,38 +13,38 @@ import org.junit.jupiter.api.Test;
//@RunWith(JUnitPlatform.class)
public class JUnit5NewFeaturesUnitTest {
private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName());
private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName());
@BeforeAll
static void setup() {
log.info("@BeforeAll - executes once before all test methods in this class");
}
@BeforeAll
static void setup() {
log.info("@BeforeAll - executes once before all test methods in this class");
}
@BeforeEach
void init() {
log.info("@BeforeEach - executes before each test method in this class");
}
@BeforeEach
void init() {
log.info("@BeforeEach - executes before each test method in this class");
}
@DisplayName("Single test successful")
@Test
void testSingleSuccessTest() {
log.info("Success");
@DisplayName("Single test successful")
@Test
void testSingleSuccessTest() {
log.info("Success");
}
}
@Test
@Disabled("Not implemented yet.")
void testShowSomething() {
}
@Test
@Disabled("Not implemented yet.")
void testShowSomething() {
}
@AfterEach
void tearDown() {
log.info("@AfterEach - executed after each test method.");
}
@AfterEach
void tearDown() {
log.info("@AfterEach - executed after each test method.");
}
@AfterAll
static void done() {
log.info("@AfterAll - executed after all test methods.");
}
@AfterAll
static void done() {
log.info("@AfterAll - executed after all test methods.");
}
}
+20 -19
View File
@@ -12,27 +12,28 @@ import org.junit.jupiter.api.TestFactory;
public class LiveTest {
private List<String> in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No"));
private List<String> out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie"));
private List<String> in = new ArrayList<>(Arrays.asList("Hello", "Yes", "No"));
private List<String> out = new ArrayList<>(Arrays.asList("Cześć", "Tak", "Nie"));
@TestFactory
public Stream<DynamicTest> translateDynamicTestsFromStream() {
@TestFactory
public Stream<DynamicTest> translateDynamicTestsFromStream() {
return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> {
int id = in.indexOf(word);
assertEquals(out.get(id), translate(word));
}));
}
return in.stream()
.map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> {
int id = in.indexOf(word);
assertEquals(out.get(id), translate(word));
}));
}
private String translate(String word) {
if ("Hello".equalsIgnoreCase(word)) {
return "Cześć";
} else if ("Yes".equalsIgnoreCase(word)) {
return "Tak";
} else if ("No".equalsIgnoreCase(word)) {
return "Nie";
}
return "Error";
}
private String translate(String word) {
if ("Hello".equalsIgnoreCase(word)) {
return "Cześć";
} else if ("Yes".equalsIgnoreCase(word)) {
return "Tak";
} else if ("No".equalsIgnoreCase(word)) {
return "Nie";
}
return "Error";
}
}
@@ -14,36 +14,36 @@ public class RepeatedTestExample {
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());
@@ -2,10 +2,10 @@ package com.baeldung;
public final class StringUtils {
public static Double convertToDouble(String str) {
if (str == null) {
return null;
}
return Double.valueOf(str);
}
public static Double convertToDouble(String str) {
if (str == null) {
return null;
}
return Double.valueOf(str);
}
}
@@ -25,13 +25,15 @@ public class TestLauncher {
//@formatter:on
TestPlan plan = LauncherFactory.create().discover(request);
TestPlan plan = LauncherFactory.create()
.discover(request);
Launcher launcher = LauncherFactory.create();
SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener();
launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener });
launcher.execute(request);
summaryGeneratingListener.getSummary().printTo(new PrintWriter(System.out));
summaryGeneratingListener.getSummary()
.printTo(new PrintWriter(System.out));
}
}
@@ -12,7 +12,9 @@ public class EmployeeDaoParameterResolver implements ParameterResolver {
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return parameterContext.getParameter().getType().equals(EmployeeJdbcDao.class);
return parameterContext.getParameter()
.getType()
.equals(EmployeeJdbcDao.class);
}
@Override
@@ -10,7 +10,9 @@ 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);
testInstance.getClass()
.getMethod("setLogger", Logger.class)
.invoke(testInstance, logger);
}
}
@@ -30,9 +30,10 @@ public class AssertionsExampleTest {
List<Integer> list = Arrays.asList(1, 2, 3);
Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0)
.intValue(), 1),
() -> Assertions.assertEquals(list.get(1)
.intValue(), 2),
.intValue(), 1), () -> Assertions.assertEquals(
list.get(1)
.intValue(),
2),
() -> Assertions.assertEquals(list.get(2)
.intValue(), 3));
}
@@ -9,42 +9,51 @@ import org.junit.jupiter.api.extension.ParameterResolver;
public class InvalidPersonParameterResolver implements ParameterResolver {
/**
* The "bad" (invalid) data for testing purposes has to go somewhere, right?
*/
public static Person[] INVALID_PERSONS = {
new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"),
new Person().setId(2L).setLastName(",Baker").setFirstName(""),
new Person().setId(3L).setLastName(null).setFirstName(null),
new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"),
new Person().setId(5L).setLastName("").setFirstName("English, Jane"),
new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */,
// TODO: ADD MORE DATA HERE
};
/**
* The "bad" (invalid) data for testing purposes has to go somewhere, right?
*/
public static Person[] INVALID_PERSONS = { new Person().setId(1L)
.setLastName("Ad_ams")
.setFirstName("Jill,"),
new Person().setId(2L)
.setLastName(",Baker")
.setFirstName(""),
new Person().setId(3L)
.setLastName(null)
.setFirstName(null),
new Person().setId(4L)
.setLastName("Daniel&")
.setFirstName("{Joseph}"),
new Person().setId(5L)
.setLastName("")
.setFirstName("English, Jane"),
new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */,
// TODO: ADD MORE DATA HERE
};
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
Object ret = null;
//
// Return a random, valid Person object if Person.class is the type of Parameter
/// to be resolved. Otherwise return null.
if (parameterContext.getParameter().getType() == Person.class) {
ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)];
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Object ret = null;
//
// Return a random, valid Person object if Person.class is the type of Parameter
/// to be resolved. Otherwise return null.
if (parameterContext.getParameter()
.getType() == Person.class) {
ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)];
}
return ret;
}
return ret;
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
boolean ret = false;
//
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter().getType() == Person.class) {
ret = true;
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
boolean ret = false;
//
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter()
.getType() == Person.class) {
ret = true;
}
return ret;
}
return ret;
}
}
@@ -9,35 +9,35 @@ package com.baeldung.param;
*/
public class Person {
private Long id;
private String lastName;
private String firstName;
private Long id;
private String lastName;
private String firstName;
public Long getId() {
return id;
}
public Long getId() {
return id;
}
public Person setId(Long id) {
this.id = id;
return this;
}
public Person setId(Long id) {
this.id = id;
return this;
}
public String getLastName() {
return lastName;
}
public String getLastName() {
return lastName;
}
public Person setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public Person setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public String getFirstName() {
return firstName;
}
public String getFirstName() {
return firstName;
}
public Person setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Person setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
}
@@ -11,132 +11,122 @@ import java.util.Arrays;
*/
public class PersonValidator {
/**
* Contrived checked exception to illustrate one possible
* way to handle validation errors (via a checked exception).
*
* @author J Steven Perry
*
*/
public static class ValidationException extends Exception {
/**
* Contrived checked exception to illustrate one possible
* way to handle validation errors (via a checked exception).
*
* @author J Steven Perry
*
*/
public static class ValidationException extends Exception {
/**
*
*/
private static final long serialVersionUID = -134518049431883102L;
// Probably should implement some more constructors, but don't want
/// to tarnish the lesson...
/**
* The one and only way to create this checked exception.
*
* @param message
* The message accompanying the exception. Should be meaningful.
*/
public ValidationException(String message) {
super(message);
}
}
private static final String[] ILLEGAL_NAME_CHARACTERS = { ",", "_", "{", "}", "!" };
/**
* Validate the first name of the specified Person object.
*
* @param person
* The Person object to validate.
*
* @return - returns true if the specified Person is valid
*
* @throws ValidationException
* - this Exception is thrown if any kind of validation error occurs.
*/
private static final long serialVersionUID = -134518049431883102L;
// Probably should implement some more constructors, but don't want
/// to tarnish the lesson...
public static boolean validateFirstName(Person person) throws ValidationException {
boolean ret = true;
// The validation rules go here.
// Naive: use simple ifs
if (person == null) {
throw new ValidationException("Person is null (not allowed)!");
}
if (person.getFirstName() == null) {
throw new ValidationException("Person FirstName is null (not allowed)!");
}
if (person.getFirstName()
.isEmpty()) {
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
}
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
throw new ValidationException("Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!");
}
return ret;
}
/**
* The one and only way to create this checked exception.
* Validate the last name of the specified Person object. Looks the same as first
* name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge.
*
* @param message
* The message accompanying the exception. Should be meaningful.
* @param person
* The Person object to validate.
*
* @return - returns true if the specified Person is valid
*
* @throws ValidationException
* - this Exception is thrown if any kind of validation error occurs.
*/
public ValidationException(String message) {
super(message);
public static boolean validateLastName(Person person) throws ValidationException {
boolean ret = true;
// The validation rules go here.
// Naive: use simple ifs
if (person == null) {
throw new ValidationException("Person is null (not allowed)!");
}
if (person.getFirstName() == null) {
throw new ValidationException("Person FirstName is null (not allowed)!");
}
if (person.getFirstName()
.isEmpty()) {
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
}
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
throw new ValidationException("Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!");
}
return ret;
}
}
private static final String[] ILLEGAL_NAME_CHARACTERS = {
",",
"_",
"{",
"}",
"!"
};
/**
* Validate the first name of the specified Person object.
*
* @param person
* The Person object to validate.
*
* @return - returns true if the specified Person is valid
*
* @throws ValidationException
* - this Exception is thrown if any kind of validation error occurs.
*/
public static boolean validateFirstName(Person person) throws ValidationException {
boolean ret = true;
// The validation rules go here.
// Naive: use simple ifs
if (person == null) {
throw new ValidationException("Person is null (not allowed)!");
/**
* Validates the specified name. If it contains any of the illegalCharacters,
* this method returns false (indicating the name is illegal). Otherwise it returns true.
*
* @param candidate
* The candidate String to validate
*
* @param illegalCharacters
* The characters the String is not allowed to have
*
* @return - boolean - true if the name is valid, false otherwise.
*/
private static boolean isStringValid(String candidate, String[] illegalCharacters) {
boolean ret = true;
for (String illegalChar : illegalCharacters) {
if (candidate.contains(illegalChar)) {
ret = false;
break;
}
}
return ret;
}
if (person.getFirstName() == null) {
throw new ValidationException("Person FirstName is null (not allowed)!");
}
if (person.getFirstName().isEmpty()) {
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
}
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
throw new ValidationException(
"Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: "
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
+ "!");
}
return ret;
}
/**
* Validate the last name of the specified Person object. Looks the same as first
* name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge.
*
* @param person
* The Person object to validate.
*
* @return - returns true if the specified Person is valid
*
* @throws ValidationException
* - this Exception is thrown if any kind of validation error occurs.
*/
public static boolean validateLastName(Person person) throws ValidationException {
boolean ret = true;
// The validation rules go here.
// Naive: use simple ifs
if (person == null) {
throw new ValidationException("Person is null (not allowed)!");
}
if (person.getFirstName() == null) {
throw new ValidationException("Person FirstName is null (not allowed)!");
}
if (person.getFirstName().isEmpty()) {
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
}
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
throw new ValidationException(
"Person LastName (" + person.getLastName() + ") may not contain any of the following characters: "
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
+ "!");
}
return ret;
}
/**
* Validates the specified name. If it contains any of the illegalCharacters,
* this method returns false (indicating the name is illegal). Otherwise it returns true.
*
* @param candidate
* The candidate String to validate
*
* @param illegalCharacters
* The characters the String is not allowed to have
*
* @return - boolean - true if the name is valid, false otherwise.
*/
private static boolean isStringValid(String candidate, String[] illegalCharacters) {
boolean ret = true;
for (String illegalChar : illegalCharacters) {
if (candidate.contains(illegalChar)) {
ret = false;
break;
}
}
return ret;
}
}
@@ -15,88 +15,88 @@ import org.junit.runner.RunWith;
@DisplayName("Testing PersonValidator")
public class PersonValidatorTest {
/**
* Nested class, uses ExtendWith
* {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver}
* to feed Test methods with "good" data.
*/
@Nested
@DisplayName("When using Valid data")
@ExtendWith(ValidPersonParameterResolver.class)
public class ValidData {
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* A valid Person object to validate.
* Nested class, uses ExtendWith
* {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver}
* to feed Test methods with "good" data.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are valid")
public void validateFirstName(Person person) {
try {
assertTrue(PersonValidator.validateFirstName(person));
} catch (PersonValidator.ValidationException e) {
fail("Exception not expected: " + e.getLocalizedMessage());
}
@Nested
@DisplayName("When using Valid data")
@ExtendWith(ValidPersonParameterResolver.class)
public class ValidData {
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* A valid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are valid")
public void validateFirstName(Person person) {
try {
assertTrue(PersonValidator.validateFirstName(person));
} catch (PersonValidator.ValidationException e) {
fail("Exception not expected: " + e.getLocalizedMessage());
}
}
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* A valid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All last names are valid")
public void validateLastName(Person person) {
try {
assertTrue(PersonValidator.validateLastName(person));
} catch (PersonValidator.ValidationException e) {
fail("Exception not expected: " + e.getLocalizedMessage());
}
}
}
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* A valid Person object to validate.
* Nested class, uses ExtendWith
* {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver}
* to feed Test methods with "bad" data.
*/
@RepeatedTest(value = 10)
@DisplayName("All last names are valid")
public void validateLastName(Person person) {
try {
assertTrue(PersonValidator.validateLastName(person));
} catch (PersonValidator.ValidationException e) {
fail("Exception not expected: " + e.getLocalizedMessage());
}
@Nested
@DisplayName("When using Invalid data")
@ExtendWith(InvalidPersonParameterResolver.class)
public class InvalidData {
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* An invalid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are invalid")
public void validateFirstName(Person person) {
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person));
}
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* An invalid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are invalid")
public void validateLastName(Person person) {
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person));
}
}
}
/**
* Nested class, uses ExtendWith
* {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver}
* to feed Test methods with "bad" data.
*/
@Nested
@DisplayName("When using Invalid data")
@ExtendWith(InvalidPersonParameterResolver.class)
public class InvalidData {
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* An invalid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are invalid")
public void validateFirstName(Person person) {
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person));
}
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* An invalid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are invalid")
public void validateLastName(Person person) {
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person));
}
}
}
@@ -9,42 +9,53 @@ import org.junit.jupiter.api.extension.ParameterResolver;
public class ValidPersonParameterResolver implements ParameterResolver {
/**
* The "good" (valid) data for testing purposes has to go somewhere, right?
*/
public static Person[] VALID_PERSONS = {
new Person().setId(1L).setLastName("Adams").setFirstName("Jill"),
new Person().setId(2L).setLastName("Baker").setFirstName("James"),
new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"),
new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"),
new Person().setId(5L).setLastName("English").setFirstName("Jane"),
new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"),
// TODO: ADD MORE DATA HERE
};
/**
* The "good" (valid) data for testing purposes has to go somewhere, right?
*/
public static Person[] VALID_PERSONS = { new Person().setId(1L)
.setLastName("Adams")
.setFirstName("Jill"),
new Person().setId(2L)
.setLastName("Baker")
.setFirstName("James"),
new Person().setId(3L)
.setLastName("Carter")
.setFirstName("Samanta"),
new Person().setId(4L)
.setLastName("Daniels")
.setFirstName("Joseph"),
new Person().setId(5L)
.setLastName("English")
.setFirstName("Jane"),
new Person().setId(6L)
.setLastName("Fontana")
.setFirstName("Enrique"),
// TODO: ADD MORE DATA HERE
};
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
Object ret = null;
//
// Return a random, valid Person object if Person.class is the type of Parameter
/// to be resolved. Otherwise return null.
if (parameterContext.getParameter().getType() == Person.class) {
ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)];
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
Object ret = null;
//
// Return a random, valid Person object if Person.class is the type of Parameter
/// to be resolved. Otherwise return null.
if (parameterContext.getParameter()
.getType() == Person.class) {
ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)];
}
return ret;
}
return ret;
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
boolean ret = false;
//
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter().getType() == Person.class) {
ret = true;
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
boolean ret = false;
//
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter()
.getType() == Person.class) {
ret = true;
}
return ret;
}
return ret;
}
}
@@ -6,7 +6,7 @@ import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@SelectPackages("com.baeldung")
//@SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class})
// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class})
public class AllTests {
}