Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -0,0 +1,124 @@
package com.baeldung.encoding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
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 ");
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenIgnoreMalformedInputSequence() throws IOException {
Assertions.assertEquals("The faade pattern is a software design pattern.", CharacterEncodingExamples.decodeText("The façade pattern is a software design pattern.", StandardCharsets.US_ASCII, CodingErrorAction.IGNORE));
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenReplaceMalformedInputSequence() throws IOException {
Assertions.assertEquals(
"The fa��ade pattern is a software design pattern.",
CharacterEncodingExamples.decodeText(
"The façade pattern is a software design pattern.",
StandardCharsets.US_ASCII,
CodingErrorAction.REPLACE));
}
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenReportMalformedInputSequence() {
Assertions.assertThrows(
MalformedInputException.class,
() -> CharacterEncodingExamples.decodeText(
"The façade pattern is a software design pattern.",
StandardCharsets.US_ASCII,
CodingErrorAction.REPORT));
}
@Test
public void givenTextFile_whenLoopOverAllCandidateEncodings_thenProduceSuitableCandidateEncodings() {
Path path = Paths.get("src/test/resources/encoding.txt");
List<Charset> allCandidateCharSets = Arrays.asList(
StandardCharsets.US_ASCII, StandardCharsets.UTF_8, StandardCharsets.ISO_8859_1);
List<Charset> suitableCharsets = new ArrayList<>();
allCandidateCharSets.forEach(charset -> {
try {
CharsetDecoder charsetDecoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT);
Reader reader = new InputStreamReader(Files.newInputStream(path), charsetDecoder);
BufferedReader bufferedReader = new BufferedReader(reader);
bufferedReader.readLine();
suitableCharsets.add(charset);
} catch (MalformedInputException ignored) {
} catch (IOException ex) {
ex.printStackTrace();
}
});
Assertions.assertEquals(suitableCharsets, Arrays.asList(StandardCharsets.UTF_8, StandardCharsets.ISO_8859_1));
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -0,0 +1,47 @@
package com.baeldung.graph;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class GraphUnitTest {
@Test
public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() {
Graph graph = createGraph();
assertEquals("[Bob, Rob, Maria, Alice, Mark]",
GraphTraversal.depthFirstTraversal(graph, "Bob").toString());
}
@Test
public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() {
Graph graph = createGraph();
assertEquals("[Bob, Alice, Rob, Mark, Maria]",
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
}
@Test
public void givenAGraph_whenRemoveVertex_thenVertedNotFound() {
Graph graph = createGraph();
assertEquals("[Bob, Alice, Rob, Mark, Maria]",
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
graph.removeVertex("Maria");
assertEquals("[Bob, Alice, Rob, Mark]",
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;
}
}
@@ -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,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);
}
}
@@ -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);
}
}
@@ -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")));
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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");
}
}
@@ -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");
}
}
@@ -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);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.junit4vstestng;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ RegistrationUnitTest.class, SignInUnitTest.class })
public class SuiteUnitTest {
}
@@ -0,0 +1,41 @@
package com.baeldung.leapyear;
import java.time.LocalDate;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.GregorianCalendar;
import org.junit.Assert;
import org.junit.Test;
public class LeapYearUnitTest {
//Before Java8
@Test
public void testLeapYearUsingGregorianCalendar () {
Assert.assertFalse(new GregorianCalendar().isLeapYear(2018));
}
//Java 8 and above
@Test
public void testLeapYearUsingJavaTimeYear () {
Assert.assertTrue(Year.isLeap(2012));
}
@Test
public void testBCYearUsingJavaTimeYear () {
Assert.assertTrue(Year.isLeap(-4));
}
@Test
public void testWrongLeapYearUsingJavaTimeYear () {
Assert.assertFalse(Year.isLeap(2018));
}
@Test
public void testLeapYearInDateUsingJavaTimeYear () {
LocalDate date = LocalDate.parse("2020-01-05", DateTimeFormatter.ISO_LOCAL_DATE);
Assert.assertTrue(Year.from(date).isLeap());
}
}
@@ -0,0 +1,24 @@
package com.baeldung.manifest;
import static org.junit.Assert.*;
import org.junit.Test;
public class ExecuteJarFileUnitTest {
private static final String ERROR_MESSAGE = "no main manifest attribute, in example.jar\n";
private static final String SUCCESS_MESSAGE = "AppExample executed!\n";
@Test
public final void givenDefaultManifest_whenManifestAttributeIsNotPresent_thenGetErrorMessage() {
String output = ExecuteJarFile.executeJarWithoutManifestAttribute();
assertEquals(ERROR_MESSAGE, output);
}
@Test
public final void givenCustomManifest_whenManifestAttributeIsPresent_thenGetSuccessMessage() {
String output = ExecuteJarFile.executeJarWithManifestAttribute();
assertEquals(SUCCESS_MESSAGE, output);
}
}
@@ -0,0 +1,190 @@
package com.baeldung.money;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle;
import org.junit.Ignore;
import org.junit.Test;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException;
import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JavaMoneyUnitManualTest {
@Test
public void givenCurrencyCode_whenString_thanExist() {
CurrencyUnit usd = Monetary.getCurrency("USD");
assertNotNull(usd);
assertEquals(usd.getCurrencyCode(), "USD");
assertEquals(usd.getNumericCode(), 840);
assertEquals(usd.getDefaultFractionDigits(), 2);
}
@Test(expected = UnknownCurrencyException.class)
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
Monetary.getCurrency("AAA");
}
@Test
public void givenAmounts_whenStringified_thanEquals() {
CurrencyUnit usd = Monetary.getCurrency("USD");
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200)
.create();
Money moneyof = Money.of(12, usd);
FastMoney fastmoneyof = FastMoney.of(2, usd);
assertEquals("USD", usd.toString());
assertEquals("USD 200", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString());
assertEquals("USD 2.00000", fastmoneyof.toString());
}
@Test
public void givenCurrencies_whenCompared_thanNotequal() {
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money oneEuro = Money.of(1, "EUR");
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
assertTrue(oneDolar.equals(Money.of(1, "USD")));
}
@Test(expected = ArithmeticException.class)
public void givenAmount_whenDivided_thanThrowsException() {
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
oneDolar.divide(3);
fail(); // if no exception
}
@Test
public void givenAmounts_whenSummed_thanCorrect() {
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
Money sumAmtCHF = (Money) monetaryAmounts
.stream()
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
assertEquals("CHF 111.35", sumAmtCHF.toString());
}
@Test
public void givenArithmetic_whenStringified_thanEqualsAmount() {
CurrencyUnit usd = Monetary.getCurrency("USD");
Money moneyof = Money.of(12, usd);
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200.50)
.create();
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money subtractedAmount = Money
.of(1, "USD")
.subtract(fstAmtUSD);
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
MonetaryAmount divideAmount = oneDolar.divide(0.25);
assertEquals("USD", usd.toString());
assertEquals("USD 1", oneDolar.toString());
assertEquals("USD 200.5", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString());
assertEquals("USD -199.5", subtractedAmount.toString());
assertEquals("USD 0.25", multiplyAmount.toString());
assertEquals("USD 4", divideAmount.toString());
}
@Test
public void givenAmount_whenRounded_thanEquals() {
MonetaryAmount fstAmtEUR = Monetary
.getDefaultAmountFactory()
.setCurrency("EUR")
.setNumber(1.30473908)
.create();
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertEquals("EUR 1.3", roundEUR.toString());
}
@Test
@Ignore("Currency providers are not always available")
public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
assertEquals("USD 1", oneDollar.toString());
assertNotNull(convertedAmountUSDtoEUR);
}
@Test
public void givenLocale_whenFormatted_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDollar);
assertEquals("USD 1", oneDollar.toString());
assertNotNull(formatUSD);
assertEquals("USD1.00", usFormatted);
}
@Test
public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US)
.set(CurrencyStyle.NAME)
.set("pattern", "00000.00 US Dollar")
.build());
String customFormatted = customFormat.format(oneDollar);
assertNotNull(customFormat);
assertEquals("USD 1", oneDollar.toString());
assertEquals("00001.00 US Dollar", customFormatted);
}
}
@@ -0,0 +1,84 @@
package com.baeldung.properties;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.Test;
public class MergePropertiesUnitTest {
@Test
public void givenTwoProperties_whenMergedUsingIteration_thenAllPropertiesInResult() {
Properties globalProperties = mergePropertiesByIteratingKeySet(propertiesA(), propertiesB());
testMergedProperties(globalProperties);
}
@Test
public void givenTwoProperties_whenMergedUsingPutAll_thenAllPropertiesInResult() {
Properties globalProperties = mergePropertiesByUsingPutAll(propertiesA(), propertiesB());
testMergedProperties(globalProperties);
}
@Test
public void givenTwoProperties_whenMergedUsingStreamAPI_thenAllPropertiesInResult() {
Properties globalProperties = mergePropertiesByUsingStreamApi(propertiesB(), propertiesA());
testMergedProperties(globalProperties);
}
private Properties mergePropertiesByIteratingKeySet(Properties... properties) {
Properties mergedProperties = new Properties();
for (Properties property : properties) {
Set<String> propertyNames = property.stringPropertyNames();
for (String name : propertyNames) {
String propertyValue = property.getProperty(name);
mergedProperties.setProperty(name, propertyValue);
}
}
return mergedProperties;
}
private Properties mergePropertiesByUsingPutAll(Properties... properties) {
Properties mergedProperties = new Properties();
for (Properties property : properties) {
mergedProperties.putAll(property);
}
return mergedProperties;
}
private Properties mergePropertiesByUsingStreamApi(Properties... properties) {
return Stream.of(properties)
.collect(Properties::new, Map::putAll, Map::putAll);
}
private Properties propertiesA() {
Properties properties = new Properties();
properties.setProperty("application.name", "my-app");
properties.setProperty("application.version", "1.0");
return properties;
}
private Properties propertiesB() {
Properties properties = new Properties();
properties.setProperty("property-1", "sample property");
properties.setProperty("property-2", "another sample property");
return properties;
}
private void testMergedProperties(Properties globalProperties) {
assertThat("There should be 4 properties", globalProperties.size(), equalTo(4));
assertEquals("Property should be", globalProperties.getProperty("application.name"), "my-app");
assertEquals("Property should be", globalProperties.getProperty("application.version"), "1.0");
assertEquals("Property should be", globalProperties.getProperty("property-1"), "sample property");
assertEquals("Property should be", globalProperties.getProperty("property-2"), "another sample property");
}
}
@@ -0,0 +1,73 @@
package com.baeldung.regexp;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
public class EscapingCharsUnitTest {
@Test
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
String strInput = "foof";
String strRegex = "foo.";
assertEquals(true, strInput.matches(strRegex));
}
@Test
public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() {
String strInput = "foof";
String strRegex = "foo\\.";
assertEquals(false, strInput.matches(strRegex));
}
@Test
public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() {
String strInput = "foo|bar|hello|world";
String strRegex = "\\Q|\\E";
assertEquals(4, strInput.split(strRegex).length);
}
@Test
public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() {
String strInput = "foo|bar|hello|world";
String strRegex = "|";
assertEquals(4, strInput.split(Pattern.quote(strRegex)).length);
}
@Test
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
String strInput = "I gave $50 to my brother."
+ "He bought candy for $35. Now he has $15 left.";
String strRegex = "$";
String strReplacement = "£";
String output = "I gave £50 to my brother."
+ "He bought candy for £35. Now he has £15 left.";
Pattern p = Pattern.compile(strRegex);
Matcher m = p.matcher(strInput);
assertThat(output, not(equalTo(m.replaceAll(strReplacement))));
}
@Test
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
String strInput = "I gave $50 to my brother."
+ "He bought candy for $35. Now he has $15 left.";
String strRegex = "\\$";
String strReplacement = "£";
String output = "I gave £50 to my brother."
+ "He bought candy for £35. Now he has £15 left.";
Pattern p = Pattern.compile(strRegex);
Matcher m = p.matcher(strInput);
assertEquals(output, m.replaceAll(strReplacement));
}
}

Some files were not shown because too many files have changed in this diff Show More