[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.abstractclasses.test;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LowercaseFileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLowercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
|
||||
BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
|
||||
|
||||
assertThat(lowercaseFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.abstractclasses.test;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UppercaseFileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUppercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
|
||||
BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
|
||||
|
||||
assertThat(uppercaseFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.asciiart;
|
||||
|
||||
import java.awt.Font;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.asciiart.AsciiArt.Settings;
|
||||
|
||||
public class AsciiArtIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() {
|
||||
AsciiArt asciiArt = new AsciiArt();
|
||||
String text = "BAELDUNG";
|
||||
Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
|
||||
|
||||
asciiArt.drawString(text, "*", settings);
|
||||
}
|
||||
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.bitwiseoperator.test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BitwiseOperatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenAndOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 & value2;
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenOrOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 | value2;
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenXorOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 ^ value2;
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneInteger_whenNotOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int result = ~value1;
|
||||
assertEquals(result, -7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int rightShift = value >> 2;
|
||||
assertEquals(3, rightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int rightShift = value >> 2;
|
||||
assertEquals(-3, rightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int leftShift = value << 2;
|
||||
assertEquals(48, leftShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int leftShift = value << 2;
|
||||
assertEquals(-48, leftShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int unsignedRightShift = value >>> 2;
|
||||
assertEquals(3, unsignedRightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int unsignedRightShift = value >>> 2;
|
||||
assertEquals(1073741821, unsignedRightShift);
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.classloader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class CustomClassLoaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
|
||||
|
||||
CustomClassLoader customClassLoader = new CustomClassLoader();
|
||||
Class<?> c = customClassLoader.findClass(PrintClassLoader.class.getName());
|
||||
|
||||
Object ob = c.newInstance();
|
||||
|
||||
Method md = c.getMethod("printClassLoaders");
|
||||
md.invoke(ob);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.classloader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PrintClassLoaderUnitTest {
|
||||
@Test(expected = ClassNotFoundException.class)
|
||||
public void givenAppClassLoader_whenParentClassLoader_thenClassNotFoundException() throws Exception {
|
||||
PrintClassLoader sampleClassLoader = (PrintClassLoader) Class.forName(PrintClassLoader.class.getName()).newInstance();
|
||||
sampleClassLoader.printClassLoaders();
|
||||
Class.forName(PrintClassLoader.class.getName(), true, PrintClassLoader.class.getClassLoader().getParent());
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.curltojava;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaCurlExamplesLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException {
|
||||
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
|
||||
processBuilder.directory(new File("/home/"));
|
||||
Process process = processBuilder.start();
|
||||
InputStream inputStream = process.getInputStream();
|
||||
// Consume the inputStream so the process can exit
|
||||
JavaCurlExamples.consumeInputStream(inputStream);
|
||||
int exitCode = process.exitValue();
|
||||
|
||||
Assert.assertEquals(0, exitCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException {
|
||||
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
|
||||
processBuilder.directory(new File("/home/"));
|
||||
Process process = processBuilder.start();
|
||||
|
||||
// Re-use processBuilder
|
||||
processBuilder.command(new String[]{"newCommand", "arguments"});
|
||||
|
||||
Assert.assertEquals(true, process.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestPost_thenCheckIfReturnContent() throws IOException {
|
||||
String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
|
||||
Process process = Runtime.getRuntime().exec(command);
|
||||
|
||||
// Get the POST result
|
||||
String content = JavaCurlExamples.inputStreamToString(process.getInputStream());
|
||||
|
||||
Assert.assertTrue(null != content && !content.isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.deserialization;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InvalidClassException;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DeserializationUnitTest {
|
||||
|
||||
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA";
|
||||
|
||||
private static long userDefinedSerialVersionUID = 1234567L;
|
||||
|
||||
/**
|
||||
* Tests the deserialization of the original "AppleProduct" (no exceptions are thrown)
|
||||
* @throws ClassNotFoundException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Test
|
||||
public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
|
||||
|
||||
assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||
|
||||
AppleProduct macBook = new AppleProduct();
|
||||
macBook.headphonePort = "headphonePort2020";
|
||||
macBook.thunderboltPort = "thunderboltPort2020";
|
||||
macBook.lightningPort = "lightningPort2020";
|
||||
|
||||
// serializes the "AppleProduct" object
|
||||
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
|
||||
|
||||
// deserializes the "AppleProduct" object
|
||||
AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
|
||||
|
||||
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
|
||||
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
|
||||
assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the deserialization of the modified (non-compatible) "AppleProduct".
|
||||
* The test should result in an InvalidClassException being thrown.
|
||||
*
|
||||
* Note: to run this test:
|
||||
* 1. Modify the value of the serialVersionUID identifier in AppleProduct.java
|
||||
* 2. Remove the @Ignore annotation
|
||||
* 3. Run the test individually (do not run the entire set of tests)
|
||||
* 4. Revert the changes made in 1 & 2 (so that you're able to re-run the tests successfully)
|
||||
*
|
||||
* @throws ClassNotFoundException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Ignore
|
||||
@Test(expected = InvalidClassException.class)
|
||||
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
|
||||
|
||||
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||
// attempts to deserialize the "AppleProduct" object
|
||||
DeserializationUtility.deSerializeObjectFromString(serializedObj);
|
||||
}
|
||||
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.encoding;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CharacterEncodingExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTextFile_whenCalledWithEncodingASCII_thenProduceIncorrectResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.readFile(
|
||||
"src/test/resources/encoding.txt", "US-ASCII"),
|
||||
"The fa��ade pattern is a software-design pattern commonly used with object-oriented programming.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTextFile_whenCalledWithEncodingUTF8_thenProduceCorrectResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.readFile(
|
||||
"src/test/resources/encoding.txt", "UTF-8"),
|
||||
"The façade pattern is a software-design pattern commonly used with object-oriented programming.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterA_whenConvertedtoBinaryWithEncodingASCII_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("A", "US-ASCII"),
|
||||
"1000001 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterA_whenConvertedtoBinaryWithEncodingUTF8_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("A", "UTF-8"),
|
||||
"1000001 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingBig5_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("語", "Big5"),
|
||||
"10111011 1111001 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingUTF8_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("語", "UTF-8"),
|
||||
"11101000 10101010 10011110 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingUTF32_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("語", "UTF-32"),
|
||||
"0 0 10001010 10011110 ");
|
||||
}
|
||||
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
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!");
|
||||
}
|
||||
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.externalizable;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ExternalizableUnitTest {
|
||||
|
||||
private final static String OUTPUT_FILE = "externalizable.txt";
|
||||
|
||||
@Test
|
||||
public void whenSerializing_thenUseExternalizable() throws IOException, ClassNotFoundException {
|
||||
|
||||
Country c = new Country();
|
||||
c.setCapital("Yerevan");
|
||||
c.setCode(374);
|
||||
c.setName("Armenia");
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
c.writeExternal(objectOutputStream);
|
||||
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
fileOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
|
||||
Country c2 = new Country();
|
||||
c2.readExternal(objectInputStream);
|
||||
|
||||
objectInputStream.close();
|
||||
fileInputStream.close();
|
||||
|
||||
assertTrue(c2.getCode() == c.getCode());
|
||||
assertTrue(c2.getName().equals(c.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInheritanceSerialization_then_UseExternalizable() throws IOException, ClassNotFoundException {
|
||||
|
||||
Region r = new Region();
|
||||
r.setCapital("Yerevan");
|
||||
r.setCode(374);
|
||||
r.setName("Armenia");
|
||||
r.setClimate("Mediterranean");
|
||||
r.setPopulation(120.000);
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
r.writeExternal(objectOutputStream);
|
||||
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
fileOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
|
||||
Region r2 = new Region();
|
||||
r2.readExternal(objectInputStream);
|
||||
|
||||
objectInputStream.close();
|
||||
fileInputStream.close();
|
||||
|
||||
assertTrue(r2.getPopulation() == null);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BufferedReaderUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileReaderUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FilesReadAllLinesUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerIntUnitTest {
|
||||
|
||||
protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException {
|
||||
List<Integer> numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
|
||||
assertTrue("File does not has 2 lines", numbers.size() == 2);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerStringUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphTraversalUnitTest {
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
Assert.assertEquals("[Bob, Rob, Maria, Alice, Mark]",
|
||||
GraphTraversal.depthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
Assert.assertEquals("[Bob, Alice, Rob, Mark, Maria]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
Graph createGraph() {
|
||||
Graph graph = new Graph();
|
||||
graph.addVertex("Bob");
|
||||
graph.addVertex("Alice");
|
||||
graph.addVertex("Mark");
|
||||
graph.addVertex("Rob");
|
||||
graph.addVertex("Maria");
|
||||
graph.addEdge("Bob", "Alice");
|
||||
graph.addEdge("Bob", "Rob");
|
||||
graph.addEdge("Alice", "Mark");
|
||||
graph.addEdge("Rob", "Mark");
|
||||
graph.addEdge("Alice", "Maria");
|
||||
graph.addEdge("Rob", "Maria");
|
||||
return graph;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.grep;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.unix4j.Unix4j;
|
||||
import static org.unix4j.Unix4j.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.unix4j.line.Line;
|
||||
import static org.unix4j.unix.Grep.*;
|
||||
import static org.unix4j.unix.cut.CutOption.*;
|
||||
|
||||
public class GrepWithUnix4JIntegrationTest {
|
||||
|
||||
private File fileToGrep;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
final String filePath = String.join(separator, new String[] { "src", "test", "resources", "dictionary.in" });
|
||||
fileToGrep = new File(filePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGrepWithSimpleString_thenCorrect() {
|
||||
int expectedLineCount = 4;
|
||||
|
||||
// grep "NINETEEN" dictionary.txt
|
||||
List<Line> lines = Unix4j.grep("NINETEEN", fileToGrep).toLineList();
|
||||
|
||||
assertEquals(expectedLineCount, lines.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInverseGrepWithSimpleString_thenCorrect() {
|
||||
int expectedLineCount = 178687;
|
||||
|
||||
// grep -v "NINETEEN" dictionary.txt
|
||||
List<Line> lines = grep(Options.v, "NINETEEN", fileToGrep).toLineList();
|
||||
|
||||
assertEquals(expectedLineCount, lines.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGrepWithRegex_thenCorrect() {
|
||||
int expectedLineCount = 151;
|
||||
|
||||
// grep -c ".*?NINE.*?" dictionary.txt
|
||||
String patternCount = grep(Options.c, ".*?NINE.*?", fileToGrep).cut(fields, ":", 1).toStringResult();
|
||||
|
||||
assertEquals(expectedLineCount, Integer.parseInt(patternCount));
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.hexToAscii;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class HexToAsciiUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenHexToAscii() {
|
||||
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||
|
||||
assertEquals(asciiString, hexToAscii(hexEquivalent));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAsciiToHex() {
|
||||
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||
|
||||
assertEquals(hexEquivalent, asciiToHex(asciiString));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static String asciiToHex(String asciiStr) {
|
||||
char[] chars = asciiStr.toCharArray();
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (char ch : chars) {
|
||||
hex.append(Integer.toHexString((int) ch));
|
||||
}
|
||||
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
private static String hexToAscii(String hexStr) {
|
||||
StringBuilder output = new StringBuilder("");
|
||||
for (int i = 0; i < hexStr.length(); i += 2) {
|
||||
String str = hexStr.substring(i, i + 2);
|
||||
output.append((char) Integer.parseInt(str, 16));
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.baeldung.java.clock;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ClockUnitTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ClockUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void givenClock_withSytemUTC_retrievesInstant() {
|
||||
|
||||
Clock clockUTC = Clock.systemUTC();
|
||||
|
||||
assertEquals(clockUTC.getZone(), ZoneOffset.UTC);
|
||||
assertEquals(clockUTC.instant().equals(null), false);
|
||||
|
||||
LOGGER.debug("UTC instant :: " + clockUTC.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_withSytem_retrievesInstant() {
|
||||
|
||||
Clock clockSystem = Clock.system(ZoneId.of("Asia/Calcutta"));
|
||||
|
||||
assertEquals(clockSystem.getZone(), ZoneId.of("Asia/Calcutta"));
|
||||
assertEquals(clockSystem.instant().equals(null), false);
|
||||
|
||||
LOGGER.debug("System zone :: " + clockSystem.getZone());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_withSytemDefaultZone_retrievesInstant() {
|
||||
|
||||
Clock clockSystemDefault = Clock.systemDefaultZone();
|
||||
|
||||
assertEquals(clockSystemDefault.getZone().equals(null), false);
|
||||
assertEquals(clockSystemDefault.instant().equals(null), false);
|
||||
|
||||
LOGGER.debug("System Default instant :: " + clockSystemDefault.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_withSytemUTC_retrievesTimeInMillis() {
|
||||
|
||||
Clock clockMillis = Clock.systemDefaultZone();
|
||||
|
||||
assertEquals(clockMillis.instant().equals(null), false);
|
||||
assertTrue(clockMillis.millis() > 0);
|
||||
|
||||
LOGGER.debug("System Default millis :: " + clockMillis.millis());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingOffset_retrievesFutureDate() {
|
||||
|
||||
Clock baseClock = Clock.systemDefaultZone();
|
||||
|
||||
// result clock will be later than baseClock
|
||||
Clock futureClock = Clock.offset(baseClock, Duration.ofHours(72));
|
||||
|
||||
assertEquals(futureClock.instant().equals(null), false);
|
||||
assertTrue(futureClock.millis() > baseClock.millis());
|
||||
|
||||
LOGGER.debug("Future Clock instant :: " + futureClock.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingOffset_retrievesPastDate() {
|
||||
Clock baseClock = Clock.systemDefaultZone();
|
||||
|
||||
// result clock will be later than baseClock
|
||||
Clock pastClock = Clock.offset(baseClock, Duration.ofHours(-72));
|
||||
|
||||
assertEquals(pastClock.instant().equals(null), false);
|
||||
assertTrue(pastClock.millis() < baseClock.millis());
|
||||
|
||||
LOGGER.debug("Past Clock instant :: " + pastClock.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingTick_retrievesInstant() {
|
||||
Clock clockDefaultZone = Clock.systemDefaultZone();
|
||||
Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(300));
|
||||
|
||||
assertEquals(clockDefaultZone.instant().equals(null), false);
|
||||
assertEquals(clocktick.instant().equals(null), false);
|
||||
assertTrue(clockDefaultZone.millis() > clocktick.millis());
|
||||
|
||||
LOGGER.debug("Clock Default Zone instant : " + clockDefaultZone.instant());
|
||||
LOGGER.debug("Clock tick instant: " + clocktick.instant());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void givenClock_usingTickDurationNegative_throwsException() {
|
||||
|
||||
Clock clockDefaultZone = Clock.systemDefaultZone();
|
||||
Clock.tick(clockDefaultZone, Duration.ofSeconds(-300));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingTickSeconds_retrievesInstant() {
|
||||
ZoneId zoneId = ZoneId.of("Asia/Calcutta");
|
||||
Clock tickSeconds = Clock.tickSeconds(zoneId);
|
||||
|
||||
assertEquals(tickSeconds.instant().equals(null), false);
|
||||
LOGGER.debug("Clock tick seconds instant :: " + tickSeconds.instant());
|
||||
|
||||
tickSeconds = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofSeconds(100));
|
||||
assertEquals(tickSeconds.instant().equals(null), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingTickMinutes_retrievesInstant() {
|
||||
|
||||
Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Calcutta"));
|
||||
|
||||
assertEquals(tickMinutes.instant().equals(null), false);
|
||||
LOGGER.debug("Clock tick seconds instant :: " + tickMinutes.instant());
|
||||
|
||||
tickMinutes = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofMinutes(5));
|
||||
assertEquals(tickMinutes.instant().equals(null), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingWithZone_retrievesInstant() {
|
||||
|
||||
ZoneId zoneSingapore = ZoneId.of("Asia/Singapore");
|
||||
Clock clockSingapore = Clock.system(zoneSingapore);
|
||||
|
||||
assertEquals(clockSingapore.instant().equals(null), false);
|
||||
LOGGER.debug("clockSingapore instant : " + clockSingapore.instant());
|
||||
|
||||
ZoneId zoneCalcutta = ZoneId.of("Asia/Calcutta");
|
||||
Clock clockCalcutta = clockSingapore.withZone(zoneCalcutta);
|
||||
assertEquals(clockCalcutta.instant().equals(null), false);
|
||||
LOGGER.debug("clockCalcutta instant : " + clockSingapore.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingGetZone_retrievesZoneId() {
|
||||
|
||||
Clock clockDefaultZone = Clock.systemDefaultZone();
|
||||
ZoneId zone = clockDefaultZone.getZone();
|
||||
|
||||
assertEquals(zone.getId().equals(null), false);
|
||||
LOGGER.debug("Default zone instant : " + clockDefaultZone.instant());
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.java.currentmethod;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* The class presents various ways of finding the name of currently executed method.
|
||||
*/
|
||||
public class CurrentlyExecutedMethodFinderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
|
||||
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
|
||||
assertEquals("givenCurrentThread_whenGetStackTrace_thenFindMethod", stackTrace[1].getMethodName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenException_whenGetStackTrace_thenFindMethod() {
|
||||
String methodName = new Exception().getStackTrace()[0].getMethodName();
|
||||
assertEquals("givenException_whenGetStackTrace_thenFindMethod", methodName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThrowable_whenGetStacktrace_thenFindMethod() {
|
||||
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
|
||||
assertEquals("givenThrowable_whenGetStacktrace_thenFindMethod", stackTrace[0].getMethodName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
|
||||
String methodName = new Object() {}.getClass().getEnclosingMethod().getName();
|
||||
assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod", methodName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocal_whenGetEnclosingMethod_thenFindMethod() {
|
||||
class Local {};
|
||||
String methodName = Local.class.getEnclosingMethod().getName();
|
||||
assertEquals("givenLocal_whenGetEnclosingMethod_thenFindMethod", methodName);
|
||||
}
|
||||
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
package com.baeldung.java.properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PropertiesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
String catalogConfigPath = rootPath + "catalog";
|
||||
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
Properties catalogProps = new Properties();
|
||||
catalogProps.load(new FileInputStream(catalogConfigPath));
|
||||
|
||||
String appVersion = appProps.getProperty("version");
|
||||
assertEquals("1.0", appVersion);
|
||||
|
||||
assertEquals("files", catalogProps.getProperty("c1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String iconConfigPath = rootPath + "icons.xml";
|
||||
Properties iconProps = new Properties();
|
||||
iconProps.loadFromXML(new FileInputStream(iconConfigPath));
|
||||
|
||||
assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
String appVersion = appProps.getProperty("version");
|
||||
String appName = appProps.getProperty("name", "defaultName");
|
||||
String appGroup = appProps.getProperty("group", "baeldung");
|
||||
String appDownloadAddr = appProps.getProperty("downloadAddr");
|
||||
|
||||
assertEquals("1.0", appVersion);
|
||||
assertEquals("TestApp", appName);
|
||||
assertEquals("baeldung", appGroup);
|
||||
assertNull(appDownloadAddr);
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
float appVerFloat = (float) appProps.get("version");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
appProps.setProperty("name", "NewAppName");
|
||||
appProps.setProperty("downloadAddr", "www.baeldung.com/downloads");
|
||||
|
||||
String newAppName = appProps.getProperty("name");
|
||||
assertEquals("NewAppName", newAppName);
|
||||
|
||||
String newAppDownloadAddr = appProps.getProperty("downloadAddr");
|
||||
assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
String versionBeforeRemoval = appProps.getProperty("version");
|
||||
assertEquals("1.0", versionBeforeRemoval);
|
||||
|
||||
appProps.remove("version");
|
||||
String versionAfterRemoval = appProps.getProperty("version");
|
||||
assertNull(versionAfterRemoval);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPropertiesStoredInFile_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
String newAppConfigPropertiesFile = rootPath + "newApp.properties";
|
||||
appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");
|
||||
|
||||
String newAppConfigXmlFile = rootPath + "newApp.xml";
|
||||
appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
|
||||
String defaultConfigPath = rootPath + "default.properties";
|
||||
Properties defaultProps = new Properties();
|
||||
defaultProps.load(new FileInputStream(defaultConfigPath));
|
||||
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties(defaultProps);
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
String appName = appProps.getProperty("name");
|
||||
String appVersion = appProps.getProperty("version");
|
||||
String defaultSite = appProps.getProperty("site");
|
||||
|
||||
assertEquals("1.0", appVersion);
|
||||
assertEquals("TestApp", appName);
|
||||
assertEquals("www.google.com", defaultSite);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertiesSize_whenPropertyFileLoaded_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appPropsPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appPropsPath));
|
||||
|
||||
appProps.list(System.out); // list all key-value pairs
|
||||
|
||||
Enumeration<Object> valueEnumeration = appProps.elements();
|
||||
while (valueEnumeration.hasMoreElements()) {
|
||||
System.out.println(valueEnumeration.nextElement());
|
||||
}
|
||||
|
||||
Enumeration<Object> keyEnumeration = appProps.keys();
|
||||
while (keyEnumeration.hasMoreElements()) {
|
||||
System.out.println(keyEnumeration.nextElement());
|
||||
}
|
||||
|
||||
int size = appProps.size();
|
||||
assertEquals(3, size);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8MapAndFlatMap {
|
||||
|
||||
@Test
|
||||
public void givenStream_whenCalledMap_thenProduceList() {
|
||||
List<String> myList = Stream.of("a", "b")
|
||||
.map(String::toUpperCase)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(asList("A", "B"), myList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
|
||||
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
|
||||
System.out.println(list);
|
||||
|
||||
System.out.println(list.stream()
|
||||
.flatMap(Collection::stream)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenCalledMap_thenProduceOptional() {
|
||||
Optional<String> s = Optional.of("test");
|
||||
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
|
||||
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
|
||||
.map(s -> Optional.of("STRING")));
|
||||
|
||||
assertEquals(Optional.of("STRING"), Optional.of("string")
|
||||
.flatMap(s -> Optional.of("STRING")));
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DivisibilityUnitTest {
|
||||
|
||||
private static int number;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
number = 40;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumber_whenDivisibleByTwo_thenCorrect() {
|
||||
assertEquals(number % 2, 0);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
@RunWith(value = Parameterized.class)
|
||||
public class ParametrizedUnitTest {
|
||||
|
||||
private int value;
|
||||
private boolean isEven;
|
||||
|
||||
public ParametrizedUnitTest(int value, boolean isEven) {
|
||||
this.value = value;
|
||||
this.isEven = isEven;
|
||||
}
|
||||
|
||||
@Parameters
|
||||
public static Collection<Object[]> data() {
|
||||
Object[][] data = new Object[][]{{1, false}, {2, true}, {4, true}};
|
||||
return Arrays.asList(data);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParametrizedNumber_ifEvenCheckOK_thenCorrect() {
|
||||
Assert.assertEquals(isEven, value % 2 == 0);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
public class RegistrationUnitTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenCalledFromSuite_thanOK() {
|
||||
LOGGER.info("Registration successful");
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SignInUnitTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SignInUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenCalledFromSuite_thanOK() {
|
||||
LOGGER.info("SignIn successful");
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringCaseUnitTest {
|
||||
|
||||
private static String data;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
data = "HELLO BAELDUNG";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenAllCaps_thenCorrect() {
|
||||
assertEquals(data.toUpperCase(), data);
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user