Move articles out of core-java-lang part 1 (#7908)

This commit is contained in:
Catalin Burcea
2019-10-03 07:02:53 +03:00
committed by Josh Cummings
parent aa88f134d3
commit 6cb034c1d8
82 changed files with 128 additions and 1250 deletions

View File

@@ -1,25 +0,0 @@
package com.baeldung.exception.error;
import org.junit.Assert;
import org.junit.Test;
public class ErrorGeneratorUnitTest {
@Test(expected = AssertionError.class)
public void whenError_thenIsNotCaughtByCatchException() {
try {
throw new AssertionError();
} catch (Exception e) {
Assert.fail(); // errors are not caught by catch exception
}
}
@Test
public void whenError_thenIsCaughtByCatchError() {
try {
throw new AssertionError();
} catch (Error e) {
// caught! -> test pass
}
}
}

View File

@@ -1,154 +0,0 @@
package com.baeldung.exception.numberformat;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Logger;
import org.junit.Test;
/**
* A set of examples tested to show cases where NumberFormatException is thrown and not thrown.
*/
public class NumberFormatExceptionUnitTest {
Logger LOG = Logger.getLogger(NumberFormatExceptionUnitTest.class.getName());
/* ---INTEGER FAIL CASES--- */
@Test(expected = NumberFormatException.class)
public void givenByteConstructor_whenAlphabetAsInput_thenFail() {
Byte byteInt = new Byte("one");
}
@Test(expected = NumberFormatException.class)
public void givenShortConstructor_whenSpaceInInput_thenFail() {
Short shortInt = new Short("2 ");
}
@Test(expected = NumberFormatException.class)
public void givenParseIntMethod_whenSpaceInInput_thenFail() {
Integer aIntPrim = Integer.parseInt("6000 ");
}
@Test(expected = NumberFormatException.class)
public void givenParseIntMethod_whenUnderscoreInInput_thenFail() {
int bIntPrim = Integer.parseInt("_6000");
}
@Test(expected = NumberFormatException.class)
public void givenIntegerValueOfMethod_whenCommaInInput_thenFail() {
Integer cIntPrim = Integer.valueOf("6,000");
}
@Test(expected = NumberFormatException.class)
public void givenBigIntegerConstructor_whenDecimalInInput_thenFail() {
BigInteger bigInteger = new BigInteger("4.0");
}
@Test(expected = NumberFormatException.class)
public void givenDecodeMethod_whenAlphabetInInput_thenFail() {
Long decodedLong = Long.decode("64403L");
}
/* ---INTEGER PASS CASES--- */
@Test
public void givenInvalidNumberInputs_whenOptimized_thenPass() {
Byte byteInt = new Byte("1");
assertEquals(1, byteInt.intValue());
Short shortInt = new Short("2 ".trim());
assertEquals(2, shortInt.intValue());
Integer aIntObj = Integer.valueOf("6");
assertEquals(6, aIntObj.intValue());
BigInteger bigInteger = new BigInteger("4");
assertEquals(4, bigInteger.intValue());
int aIntPrim = Integer.parseInt("6000 ".trim());
assertEquals(6000, aIntPrim);
int bIntPrim = Integer.parseInt("_6000".replaceAll("_", ""));
assertEquals(6000, bIntPrim);
int cIntPrim = Integer.parseInt("-6000");
assertEquals(-6000, cIntPrim);
Long decodeInteger = Long.decode("644032334");
assertEquals(644032334L, decodeInteger.longValue());
}
/* ---DOUBLE FAIL CASES--- */
@Test(expected = NumberFormatException.class)
public void givenFloatConstructor_whenAlphabetInInput_thenFail() {
Float floatDecimalObj = new Float("one.1");
}
@Test(expected = NumberFormatException.class)
public void givenDoubleConstructor_whenAlphabetInInput_thenFail() {
Double doubleDecimalObj = new Double("two.2");
}
@Test(expected = NumberFormatException.class)
public void givenBigDecimalConstructor_whenSpecialCharsInInput_thenFail() {
BigDecimal bigDecimalObj = new BigDecimal("3_0.3");
}
@Test(expected = NumberFormatException.class)
public void givenParseDoubleMethod_whenCommaInInput_thenFail() {
double aDoublePrim = Double.parseDouble("4000,1");
}
/* ---DOUBLE PASS CASES--- */
@Test
public void givenDoubleConstructor_whenDecimalInInput_thenPass() {
Double doubleDecimalObj = new Double("2.2");
assertEquals(2.2, doubleDecimalObj.doubleValue(), 0);
}
@Test
public void givenDoubleValueOfMethod_whenMinusInInput_thenPass() {
Double aDoubleObj = Double.valueOf("-6000");
assertEquals(-6000, aDoubleObj.doubleValue(), 0);
}
@Test
public void givenUsDecimalNumber_whenParsedWithNumberFormat_thenPass() throws ParseException {
Number parsedNumber = parseNumberWithLocale("4000.1", Locale.US);
assertEquals(4000.1, parsedNumber);
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
assertEquals(4000, parsedNumber.intValue());
}
/**
* In most European countries (for example, France), comma is used as decimal in place of period.
* @throws ParseException if the input string contains special characters other than comma or decimal.
* In this test case, anything after decimal (period) is dropped when a European locale is set.
*/
@Test
public void givenEuDecimalNumberHasComma_whenParsedWithNumberFormat_thenPass() throws ParseException {
Number parsedNumber = parseNumberWithLocale("4000,1", Locale.FRANCE);
LOG.info("Number parsed is: " + parsedNumber);
assertEquals(4000.1, parsedNumber);
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
assertEquals(4000, parsedNumber.intValue());
}
/**
* Converts a string into a number retaining all decimals, and symbols valid in a locale.
* @param number the input string for a number.
* @param locale the locale to consider while parsing a number.
* @return the generic number object which can represent multiple number types.
* @throws ParseException when input contains invalid characters.
*/
private Number parseNumberWithLocale(String number, Locale locale) throws ParseException {
locale = locale == null ? Locale.getDefault() : locale;
NumberFormat numberFormat = NumberFormat.getInstance(locale);
return numberFormat.parse(number);
}
}

View File

@@ -1,55 +0,0 @@
package com.baeldung.exceptions;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.FileNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Tests the {@link CheckedUncheckedExceptions}.
*/
public class CheckedUncheckedExceptionsUnitTest {
@Test
public void whenFileNotExist_thenThrowException() {
assertThrows(FileNotFoundException.class, () -> {
CheckedUncheckedExceptions.checkedExceptionWithThrows();
});
}
@Test
public void whenTryCatchExcetpion_thenSuccess() {
try {
CheckedUncheckedExceptions.checkedExceptionWithTryCatch();
} catch (Exception e) {
Assertions.fail(e.getMessage());
}
}
@Test
public void whenDivideByZero_thenThrowException() {
assertThrows(ArithmeticException.class, () -> {
CheckedUncheckedExceptions.divideByZero();
});
}
@Test
public void whenInvalidFile_thenThrowException() {
assertThrows(IncorrectFileNameException.class, () -> {
CheckedUncheckedExceptions.checkFile("wrongFileName.txt");
});
}
@Test
public void whenNullOrEmptyFile_thenThrowException() {
assertThrows(NullOrEmptyException.class, () -> {
CheckedUncheckedExceptions.checkFile(null);
});
assertThrows(NullOrEmptyException.class, () -> {
CheckedUncheckedExceptions.checkFile("");
});
}
}

View File

@@ -1,64 +0,0 @@
package com.baeldung.exceptions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class GlobalExceptionHandlerUnitTest {
@Mock
private Appender<ILoggingEvent> mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
@Before
public void setup() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.addAppender(mockAppender);
Handler globalExceptionHandler = new Handler();
Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
}
@After
public void teardown() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.detachAppender(mockAppender);
}
@Test
public void whenArithmeticException_thenUseUncaughtExceptionHandler() throws InterruptedException {
Thread globalExceptionHandlerThread = new Thread() {
public void run() {
GlobalExceptionHandler globalExceptionHandlerObj = new GlobalExceptionHandler();
globalExceptionHandlerObj.performArithmeticOperation(99, 0);
}
};
globalExceptionHandlerThread.start();
globalExceptionHandlerThread.join();
verify(mockAppender).doAppend(captorLoggingEvent.capture());
LoggingEvent loggingEvent = captorLoggingEvent.getValue();
assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO);
assertThat(loggingEvent.getFormattedMessage()).isEqualTo("Unhandled exception caught!");
}
}

View File

@@ -1,114 +0,0 @@
package com.baeldung.exceptions;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import static com.baeldung.exceptions.RootCauseFinder.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the {@link RootCauseFinder}.
*/
public class RootCauseFinderUnitTest {
@Test
public void givenBirthDate_whenCalculatingAge_thenAgeReturned() {
try {
int age = AgeCalculator.calculateAge("1990-01-01");
Assertions.assertEquals(1990, LocalDate
.now()
.minus(age, ChronoUnit.YEARS)
.getYear());
} catch (CalculationException e) {
Assertions.fail(e.getMessage());
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof IllegalArgumentException);
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseNotFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof IllegalArgumentException);
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(Throwables.getRootCause(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(Throwables.getRootCause(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(Throwables.getRootCause(ex) instanceof IllegalArgumentException);
}
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.exceptions.classnotfoundexception;
import org.junit.Test;
public class ClassNotFoundExceptionUnitTest {
@Test(expected = ClassNotFoundException.class)
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.exceptions.customexception;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import org.junit.Test;
public class IncorrectFileExtensionExceptionUnitTest {
@Test
public void testWhenCorrectFileExtensionGiven_ReceivesNoException() throws IncorrectFileNameException {
assertThat(FileManager.getFirstLine("correctFileNameWithProperExtension.txt")).isEqualTo("Default First Line");
}
@Test(expected = IncorrectFileExtensionException.class)
public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("src");
sBuffer.append(File.separator);
sBuffer.append("test");
sBuffer.append(File.separator);
sBuffer.append("resources");
sBuffer.append(File.separator);
sBuffer.append("correctFileNameWithoutProperExtension");
FileManager.getFirstLine(sBuffer.toString());
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.exceptions.customexception;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class IncorrectFileNameExceptionUnitTest {
@Test(expected = IncorrectFileNameException.class)
public void testWhenIncorrectFileNameExceptionThrown_ReceivesIncorrectFileNameException() throws IncorrectFileNameException {
FileManager.getFirstLine("wrongFileName.txt");
}
@Test
public void testWhenCorrectFileNameExceptionThrown_ReceivesNoException() throws IncorrectFileNameException {
assertThat(FileManager.getFirstLine("correctFileName.txt")).isEqualTo("Default First Line");
}
}

View File

@@ -0,0 +1,80 @@
package com.baeldung.exceptions.exceptionhandling;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ExceptionsUnitTest {
Exceptions exceptions = new Exceptions();
@Test
public void getPlayers() {
assertThatThrownBy(() -> exceptions.getPlayers())
.isInstanceOf(NoSuchFileException.class);
}
@Test
public void loadAllPlayers() {
assertThatThrownBy(() -> exceptions.loadAllPlayers(""))
.isInstanceOf(IllegalStateException.class);
}
@Test
public void getPlayerScoreThrows() {
assertThatThrownBy(() -> exceptions.getPlayerScoreThrows(""))
.isInstanceOf(FileNotFoundException.class);
}
@Test
public void getPlayerScoreTryCatch() {
assertThatThrownBy(() -> exceptions.getPlayerScoreTryCatch(""))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void getPlayerScoreFinally() {
assertThatThrownBy(() -> exceptions.getPlayerScoreFinally(""))
.isInstanceOf(FileNotFoundException.class);
}
@Test
public void loadAllPlayersThrowingChecked() {
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingChecked(""))
.isInstanceOf(TimeoutException.class);
}
@Test
public void loadAllPlayersThrowingUnchecked() {
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingUnchecked(""))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void loadAllPlayersWrapping() {
assertThatThrownBy(() -> exceptions.loadAllPlayersWrapping(""))
.isInstanceOf(IOException.class);
}
@Test
public void loadAllPlayersRethrowing() {
assertThatThrownBy(() -> exceptions.loadAllPlayersRethrowing(""))
.isInstanceOf(PlayerLoadException.class);
}
@Test
public void loadAllPlayersThrowable() {
assertThatThrownBy(() -> exceptions.loadAllPlayersThrowable(""))
.isInstanceOf(NullPointerException.class);
}
@Test
public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() {
assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2(""))
.isInstanceOf(PlayerScoreException.class);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.exceptions.noclassdeffounderror;
import org.junit.Test;
public class NoClassDefFoundErrorUnitTest {
@Test(expected = NoClassDefFoundError.class)
public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() {
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
sample.getClassWithInitErrors();
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.exceptions.sneakythrows;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class SneakyRunnableUnitTest {
@Test
public void whenCallSneakyRunnableMethod_thenThrowException() {
try {
new SneakyRunnable().run();
} catch (Exception e) {
assertEquals(InterruptedException.class, e.getStackTrace());
}
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.exceptions.sneakythrows;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class SneakyThrowsUnitTest {
@Test
public void whenCallSneakyMethod_thenThrowSneakyException() {
try {
SneakyThrows.throwsSneakyIOException();
} catch (Exception ex) {
assertEquals("sneaky", ex.getMessage().toString());
}
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.exceptions.stackoverflowerror;
import org.junit.Test;
public class AccountHolderManualTest {
@Test(expected = StackOverflowError.class)
public void whenInstanciatingAccountHolder_thenThrowsException() {
AccountHolder holder = new AccountHolder();
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.exceptions.stackoverflowerror;
import org.junit.Test;
public class CyclicDependancyManualTest {
@Test(expected = StackOverflowError.class)
public void whenInstanciatingClassOne_thenThrowsException() {
ClassOne obj = new ClassOne();
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.exceptions.stackoverflowerror;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class InfiniteRecursionWithTerminationConditionManualTest {
@Test
public void givenPositiveIntNoOne_whenCalcFact_thenCorrectlyCalc() {
int numToCalcFactorial = 1;
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
assertEquals(1, irtc.calculateFactorial(numToCalcFactorial));
}
@Test
public void givenPositiveIntGtOne_whenCalcFact_thenCorrectlyCalc() {
int numToCalcFactorial = 5;
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
assertEquals(120, irtc.calculateFactorial(numToCalcFactorial));
}
@Test(expected = StackOverflowError.class)
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
int numToCalcFactorial = -1;
InfiniteRecursionWithTerminationCondition irtc = new InfiniteRecursionWithTerminationCondition();
irtc.calculateFactorial(numToCalcFactorial);
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.exceptions.stackoverflowerror;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class RecursionWithCorrectTerminationConditionManualTest {
@Test
public void givenNegativeInt_whenCalcFact_thenCorrectlyCalc() {
int numToCalcFactorial = -1;
RecursionWithCorrectTerminationCondition rctc = new RecursionWithCorrectTerminationCondition();
assertEquals(1, rctc.calculateFactorial(numToCalcFactorial));
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.exceptions.stackoverflowerror;
import org.junit.Test;
public class UnintendedInfiniteRecursionManualTest {
@Test(expected = StackOverflowError.class)
public void givenPositiveIntNoOne_whenCalFact_thenThrowsException() {
int numToCalcFactorial = 1;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
uir.calculateFactorial(numToCalcFactorial);
}
@Test(expected = StackOverflowError.class)
public void givenPositiveIntGtOne_whenCalcFact_thenThrowsException() {
int numToCalcFactorial = 2;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
uir.calculateFactorial(numToCalcFactorial);
}
@Test(expected = StackOverflowError.class)
public void givenNegativeInt_whenCalcFact_thenThrowsException() {
int numToCalcFactorial = -1;
UnintendedInfiniteRecursion uir = new UnintendedInfiniteRecursion();
uir.calculateFactorial(numToCalcFactorial);
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.exceptions.throwvsthrows;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SimpleServiceUnitTest {
SimpleService simpleService = new SimpleService();
@Test
void whenSQLExceptionIsThrown_thenShouldBeRethrownWithWrappedException() {
assertThrows(DataAccessException.class,
() -> simpleService.wrappingException());
}
@Test
void whenCalled_thenNullPointerExceptionIsThrown() {
assertThrows(NullPointerException.class,
() -> simpleService.runtimeNullPointerException());
}
}

View File

@@ -1,92 +0,0 @@
package com.baeldung.java8;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Scanner;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JavaTryWithResourcesLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaTryWithResourcesLongRunningUnitTest.class);
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
private Date resource1Date, resource2Date;
// tests
/* Example for using Try_with_resources */
@Test
public void whenWritingToStringWriter_thenCorrectlyWritten() {
final StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw, true)) {
pw.print(TEST_STRING_HELLO_WORLD);
}
Assert.assertEquals(sw.getBuffer()
.toString(), TEST_STRING_HELLO_WORLD);
}
/* Example for using multiple resources */
@Test
public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() {
final StringWriter sw = new StringWriter();
try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) {
while (sc.hasNext()) {
pw.print(sc.nextLine());
}
}
Assert.assertEquals(sw.getBuffer()
.toString(), TEST_STRING_HELLO_WORLD);
}
/* Example to show order in which the resources are closed */
@Test
public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception {
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
af.doSomething();
as.doSomething();
}
Assert.assertTrue(resource1Date.after(resource2Date));
}
class AutoCloseableResourcesFirst implements AutoCloseable {
public AutoCloseableResourcesFirst() {
LOG.debug("Constructor -> AutoCloseableResources_First");
}
public void doSomething() {
LOG.debug("Something -> AutoCloseableResources_First");
}
@Override
public void close() throws Exception {
LOG.debug("Closed AutoCloseableResources_First");
resource1Date = new Date();
}
}
class AutoCloseableResourcesSecond implements AutoCloseable {
public AutoCloseableResourcesSecond() {
LOG.debug("Constructor -> AutoCloseableResources_Second");
}
public void doSomething() {
LOG.debug("Something -> AutoCloseableResources_Second");
}
@Override
public void close() throws Exception {
LOG.debug("Closed AutoCloseableResources_Second");
resource2Date = new Date();
Thread.sleep(10000);
}
}
}

View File

@@ -1,43 +0,0 @@
package com.baeldung.optional;
import org.junit.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PersonRepositoryUnitTest {
PersonRepository personRepository = new PersonRepository();
@Test
public void whenIdIsNull_thenExceptionIsThrown() {
assertThrows(IllegalArgumentException.class,
() ->
Optional
.ofNullable(personRepository.findNameById(null))
.orElseThrow(IllegalArgumentException::new));
}
@Test
public void whenIdIsNonNull_thenNoExceptionIsThrown() {
assertAll(
() ->
Optional
.ofNullable(personRepository.findNameById("id"))
.orElseThrow(RuntimeException::new));
}
@Test
public void whenIdNonNull_thenReturnsNameUpperCase() {
String name = Optional
.ofNullable(personRepository.findNameById("id"))
.map(String::toUpperCase)
.orElseThrow(RuntimeException::new);
assertEquals("NAME", name);
}
}