4- Fourth commit for core-java module splitting. This commit includes:
* to core-java-lang: * https://www.baeldung.com/java-stack-overflow-error * https://www.baeldung.com/java-new-custom-exception * https://www.baeldung.com/java-exceptions * https://www.baeldung.com/java-final-finally-finalize * https://www.baeldung.com/java-static-dynamic-binding * https://www.baeldung.com/java-throw-throws * https://www.baeldung.com/java-synthetic * https://www.baeldung.com/java-switch * https://www.baeldung.com/modulo-java * https://www.baeldung.com/java-ternary-operator
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class Animal {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(Animal.class);
|
||||
|
||||
public void makeNoise() {
|
||||
logger.info("generic animal noise");
|
||||
}
|
||||
|
||||
public void makeNoise(Integer repetitions) {
|
||||
while(repetitions != 0) {
|
||||
logger.info("generic animal noise countdown " + repetitions);
|
||||
repetitions -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class AnimalActivity {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class);
|
||||
|
||||
|
||||
public static void sleep(Animal animal) {
|
||||
logger.info("Animal is sleeping");
|
||||
}
|
||||
|
||||
public static void sleep(Cat cat) {
|
||||
logger.info("Cat is sleeping");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Animal animal = new Animal();
|
||||
|
||||
//calling methods of animal object
|
||||
animal.makeNoise();
|
||||
|
||||
animal.makeNoise(3);
|
||||
|
||||
|
||||
//assigning a dog object to reference of type Animal
|
||||
Animal catAnimal = new Cat();
|
||||
|
||||
catAnimal.makeNoise();
|
||||
|
||||
// calling static function
|
||||
AnimalActivity.sleep(catAnimal);
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
}
|
||||
18
core-java-lang/src/main/java/com/baeldung/binding/Cat.java
Normal file
18
core-java-lang/src/main/java/com/baeldung/binding/Cat.java
Normal file
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 25-07-2018.
|
||||
*/
|
||||
public class Cat extends Animal {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(Cat.class);
|
||||
|
||||
public void makeNoise() {
|
||||
|
||||
logger.info("meow");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
public static String getFirstLine(String fileName) throws IncorrectFileNameException {
|
||||
try (Scanner file = new Scanner(new File(fileName))) {
|
||||
if (file.hasNextLine()) {
|
||||
return file.nextLine();
|
||||
} else {
|
||||
throw new IllegalArgumentException("Non readable file");
|
||||
}
|
||||
} catch (FileNotFoundException err) {
|
||||
if (!isCorrectFileName(fileName)) {
|
||||
throw new IncorrectFileNameException("Incorrect filename : " + fileName, err);
|
||||
}
|
||||
// Logging etc
|
||||
} catch (IllegalArgumentException err) {
|
||||
if (!containsExtension(fileName)) {
|
||||
throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err);
|
||||
}
|
||||
// Other error cases and logging
|
||||
}
|
||||
return "Default First Line";
|
||||
}
|
||||
|
||||
private static boolean containsExtension(String fileName) {
|
||||
if (fileName.contains(".txt") || fileName.contains(".doc"))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isCorrectFileName(String fileName) {
|
||||
if (fileName.equals("wrongFileName.txt"))
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileExtensionException extends RuntimeException{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileExtensionException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.customexception;
|
||||
|
||||
public class IncorrectFileNameException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public IncorrectFileNameException(String errorMessage, Throwable err) {
|
||||
super(errorMessage, err);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Exceptions {
|
||||
|
||||
private final static Logger logger = Logger.getLogger("ExceptionLogging");
|
||||
|
||||
public static List<Player> getPlayers() throws IOException {
|
||||
Path path = Paths.get("players.dat");
|
||||
List<String> players = Files.readAllLines(path);
|
||||
|
||||
return players.stream()
|
||||
.map(Player::new)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayers(String playersFile) throws IOException{
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch(IOException ex) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryCatch(String playerFile) {
|
||||
try {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException noFile) {
|
||||
throw new IllegalArgumentException("File not found");
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryCatchRecovery(String playerFile) {
|
||||
try {
|
||||
Scanner contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch ( FileNotFoundException noFile ) {
|
||||
logger.warning("File not found, resetting score.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreFinally(String playerFile) throws FileNotFoundException {
|
||||
Scanner contents = null;
|
||||
try {
|
||||
contents = new Scanner(new File(playerFile));
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} finally {
|
||||
if (contents != null) {
|
||||
contents.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreTryWithResources(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException e ) {
|
||||
logger.warning("File not found, resetting score.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreMultipleCatchBlocks(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (IOException e) {
|
||||
logger.warning("Player file wouldn't load!");
|
||||
return 0;
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warning("Player file was corrupted!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreMultipleCatchBlocksAlternative(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile)) ) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (FileNotFoundException e) {
|
||||
logger.warning("Player file not found!");
|
||||
return 0;
|
||||
} catch (IOException e) {
|
||||
logger.warning("Player file wouldn't load!");
|
||||
return 0;
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warning("Player file was corrupted!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreUnionCatchBlocks(String playerFile) {
|
||||
try (Scanner contents = new Scanner(new File(playerFile))) {
|
||||
return Integer.parseInt(contents.nextLine());
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
logger.warning("Failed to load score!");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowingChecked(String playersFile) throws TimeoutException {
|
||||
boolean tooLong = true;
|
||||
|
||||
while (!tooLong) {
|
||||
// ... potentially long operation
|
||||
}
|
||||
throw new TimeoutException("This operation took too long");
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowingUnchecked(String playersFile) throws TimeoutException {
|
||||
if(!isFilenameValid(playersFile)) {
|
||||
throw new IllegalArgumentException("Filename isn't valid!");
|
||||
}
|
||||
return null;
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersWrapping(String playersFile) throws IOException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException io) {
|
||||
throw io;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException io) {
|
||||
throw new PlayerLoadException(io);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Player> loadAllPlayersThrowable(String playersFile) {
|
||||
try {
|
||||
throw new NullPointerException();
|
||||
} catch ( Throwable t ) {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
class FewerExceptions extends Exceptions {
|
||||
@Override
|
||||
public List<Player> loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException
|
||||
return null;
|
||||
// overridden
|
||||
}
|
||||
}
|
||||
|
||||
public void throwAsGotoAntiPattern() throws MyException {
|
||||
try {
|
||||
// bunch of code
|
||||
throw new MyException();
|
||||
// second bunch of code
|
||||
} catch ( MyException e ) {
|
||||
// third bunch of code
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
|
||||
try {
|
||||
// ...
|
||||
} catch (Exception e) {} // <== catch and swallow
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
|
||||
try {
|
||||
// ...
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
|
||||
try {
|
||||
throw new IOException();
|
||||
} catch (IOException e) {
|
||||
throw new PlayerScoreException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
|
||||
int score = 0;
|
||||
try {
|
||||
throw new IOException();
|
||||
} finally {
|
||||
return score; // <== the IOException is dropped
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isFilenameValid(String name) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class MyException extends Throwable {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class Player {
|
||||
|
||||
public int id;
|
||||
public String name;
|
||||
|
||||
public Player(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class PlayerLoadException extends Exception {
|
||||
|
||||
public PlayerLoadException(IOException io) {
|
||||
super(io);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class PlayerScoreException extends Exception {
|
||||
|
||||
public PlayerScoreException(Exception e) {
|
||||
super(e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.exceptionhandling;
|
||||
|
||||
public class TimeoutException extends Exception {
|
||||
|
||||
public TimeoutException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.keywords.finalize;
|
||||
|
||||
public class FinalizeObject {
|
||||
|
||||
@Override
|
||||
protected void finalize() throws Throwable {
|
||||
System.out.println("Execute finalize method");
|
||||
super.finalize();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
FinalizeObject object = new FinalizeObject();
|
||||
object = null;
|
||||
System.gc();
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.keywords.finalkeyword;
|
||||
|
||||
public final class Child extends Parent {
|
||||
|
||||
@Override
|
||||
void method1(int arg1, final int arg2) {
|
||||
// OK
|
||||
}
|
||||
|
||||
/* @Override
|
||||
void method2() {
|
||||
// Compilation error
|
||||
}*/
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.keywords.finalkeyword;
|
||||
|
||||
/*public class GrandChild extends Child {
|
||||
// Compilation error
|
||||
}*/
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.keywords.finalkeyword;
|
||||
|
||||
public class Parent {
|
||||
|
||||
int field1 = 1;
|
||||
final int field2 = 2;
|
||||
|
||||
Parent() {
|
||||
field1 = 2; // OK
|
||||
// field2 = 3; // Compilation error
|
||||
}
|
||||
|
||||
void method1(int arg1, final int arg2) {
|
||||
arg1 = 2; // OK
|
||||
// arg2 = 3; // Compilation error
|
||||
}
|
||||
|
||||
final void method2() {
|
||||
final int localVar = 2; // OK
|
||||
// localVar = 3; // Compilation error
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.keywords.finallykeyword;
|
||||
|
||||
public class FinallyExample {
|
||||
|
||||
public static void main(String args[]) throws Exception {
|
||||
try {
|
||||
System.out.println("Execute try block");
|
||||
throw new Exception();
|
||||
} catch (Exception e) {
|
||||
System.out.println("Execute catch block");
|
||||
} finally {
|
||||
System.out.println("Execute finally block");
|
||||
}
|
||||
|
||||
try {
|
||||
System.out.println("Execute try block");
|
||||
} finally {
|
||||
System.out.println("Execute finally block");
|
||||
}
|
||||
|
||||
try {
|
||||
System.out.println("Execute try block");
|
||||
throw new Exception();
|
||||
} finally {
|
||||
System.out.println("Execute finally block");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class AccountHolder {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
AccountHolder jointAccountHolder = new AccountHolder();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class ClassOne {
|
||||
private int oneValue;
|
||||
private ClassTwo clsTwoInstance = null;
|
||||
|
||||
public ClassOne() {
|
||||
oneValue = 0;
|
||||
clsTwoInstance = new ClassTwo();
|
||||
}
|
||||
|
||||
public ClassOne(int oneValue, ClassTwo clsTwoInstance) {
|
||||
this.oneValue = oneValue;
|
||||
this.clsTwoInstance = clsTwoInstance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class ClassTwo {
|
||||
private int twoValue;
|
||||
private ClassOne clsOneInstance = null;
|
||||
|
||||
public ClassTwo() {
|
||||
twoValue = 10;
|
||||
clsOneInstance = new ClassOne();
|
||||
}
|
||||
|
||||
public ClassTwo(int twoValue, ClassOne clsOneInstance) {
|
||||
this.twoValue = twoValue;
|
||||
this.clsOneInstance = clsOneInstance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class InfiniteRecursionWithTerminationCondition {
|
||||
public int calculateFactorial(final int number) {
|
||||
return number == 1 ? 1 : number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class RecursionWithCorrectTerminationCondition {
|
||||
public int calculateFactorial(final int number) {
|
||||
return number <= 1 ? 1 : number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
public class UnintendedInfiniteRecursion {
|
||||
public int calculateFactorial(int number) {
|
||||
return number * calculateFactorial(number - 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.switchstatement;
|
||||
|
||||
public class SwitchStatement {
|
||||
|
||||
public String exampleOfIF(String animal) {
|
||||
|
||||
String result;
|
||||
|
||||
if (animal.equals("DOG") || animal.equals("CAT")) {
|
||||
result = "domestic animal";
|
||||
} else if (animal.equals("TIGER")) {
|
||||
result = "wild animal";
|
||||
} else {
|
||||
result = "unknown animal";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String exampleOfSwitch(String animal) {
|
||||
|
||||
String result;
|
||||
|
||||
switch (animal) {
|
||||
case "DOG":
|
||||
case "CAT":
|
||||
result = "domestic animal";
|
||||
break;
|
||||
case "TIGER":
|
||||
result = "wild animal";
|
||||
break;
|
||||
default:
|
||||
result = "unknown animal";
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String forgetBreakInSwitch(String animal) {
|
||||
|
||||
String result;
|
||||
|
||||
switch (animal) {
|
||||
|
||||
case "DOG":
|
||||
System.out.println("domestic animal");
|
||||
result = "domestic animal";
|
||||
|
||||
default:
|
||||
System.out.println("unknown animal");
|
||||
result = "unknown animal";
|
||||
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String constantCaseValue(String animal) {
|
||||
|
||||
String result = "";
|
||||
|
||||
final String dog = "DOG";
|
||||
|
||||
switch (animal) {
|
||||
|
||||
case dog:
|
||||
result = "domestic animal";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.synthetic;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* Class which contains a synthetic bridge method.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class BridgeMethodDemo implements Comparator<Integer> {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public int compare(Integer o1, Integer o2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.synthetic;
|
||||
|
||||
/**
|
||||
* Wrapper for a class which contains a synthetic constructor.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SyntheticConstructorDemo {
|
||||
|
||||
/**
|
||||
* We need to instantiate the {@link NestedClass} using a private
|
||||
* constructor from the enclosing instance in order to generate a synthetic
|
||||
* constructor.
|
||||
*/
|
||||
private NestedClass nestedClass = new NestedClass();
|
||||
|
||||
/**
|
||||
* Class which contains a synthetic constructor.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
class NestedClass {
|
||||
|
||||
/**
|
||||
* In order to generate a synthetic constructor, this class must have a
|
||||
* private constructor.
|
||||
*/
|
||||
private NestedClass() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.synthetic;
|
||||
|
||||
/**
|
||||
* Wrapper for a class which contains a synthetic field reference to the outer
|
||||
* class.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SyntheticFieldDemo {
|
||||
|
||||
/**
|
||||
* Class which contains a synthetic field reference to the outer class.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
class NestedClass {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.synthetic;
|
||||
|
||||
/**
|
||||
* Wrapper for a class which contains two synthetic methods accessors to a
|
||||
* private field.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SyntheticMethodDemo {
|
||||
|
||||
/**
|
||||
* Class which contains two synthetic methods accessors to a private field.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
class NestedClass {
|
||||
|
||||
/**
|
||||
* Field for which will be generated synthetic methods accessors. It's
|
||||
* important that this field is private for this purpose.
|
||||
*/
|
||||
private String nestedField;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the private nested field. We need to read the nested field in order
|
||||
* to generate the synthetic getter.
|
||||
*
|
||||
* @return the {@link NestedClass#nestedField}
|
||||
*/
|
||||
public String getNestedField() {
|
||||
return new NestedClass().nestedField;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the private nested field. We need to write the nested field in order
|
||||
* to generate the synthetic setter.
|
||||
*
|
||||
* @param nestedField
|
||||
* the {@link NestedClass#nestedField}
|
||||
*/
|
||||
public void setNestedField(String nestedField) {
|
||||
new NestedClass().nestedField = nestedField;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
public class DataAccessException extends RuntimeException {
|
||||
|
||||
public DataAccessException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
import com.sun.mail.iap.ConnectionException;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.net.SocketException;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) throws FileNotFoundException {
|
||||
TryCatch tryCatch = new TryCatch();
|
||||
|
||||
try {
|
||||
tryCatch.execute();
|
||||
} catch (ConnectionException | SocketException ex) {
|
||||
System.out.println("IOException");
|
||||
} catch (Exception ex) {
|
||||
System.out.println("General exception");
|
||||
}
|
||||
|
||||
checkedException();
|
||||
checkedExceptionWithThrows();
|
||||
}
|
||||
|
||||
private static void checkedExceptionWithThrows() throws FileNotFoundException {
|
||||
File file = new File("not_existing_file.txt");
|
||||
FileInputStream stream = new FileInputStream(file);
|
||||
}
|
||||
|
||||
private static void checkedException() {
|
||||
File file = new File("not_existing_file.txt");
|
||||
try {
|
||||
FileInputStream stream = new FileInputStream(file);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public List<String> findAll() throws SQLException {
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class SimpleService {
|
||||
|
||||
private PersonRepository personRepository = new PersonRepository();
|
||||
|
||||
public void wrappingException() {
|
||||
try {
|
||||
personRepository.findAll();
|
||||
} catch (SQLException e) {
|
||||
throw new DataAccessException("SQL Exception", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void runtimeNullPointerException() {
|
||||
String a = null;
|
||||
a.length();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
import com.sun.mail.iap.ConnectionException;
|
||||
|
||||
import java.net.SocketException;
|
||||
|
||||
public class TryCatch {
|
||||
|
||||
public void execute() throws SocketException, ConnectionException, Exception {
|
||||
//code that would throw any of: SocketException, ConnectionException, Exception
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.LoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
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 static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
*https://gist.github.com/bloodredsun/a041de13e57bf3c6c040
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
|
||||
public class AnimalActivityUnitTest {
|
||||
|
||||
@Mock
|
||||
private Appender mockAppender;
|
||||
@Captor
|
||||
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.addAppender(mockAppender);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.detachAppender(mockAppender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnimalReference__whenRefersAnimalObject_shouldCallFunctionWithAnimalParam() {
|
||||
|
||||
Animal animal = new Animal();
|
||||
|
||||
AnimalActivity.sleep(animal);
|
||||
|
||||
verify(mockAppender).doAppend(captorLoggingEvent.capture());
|
||||
|
||||
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
|
||||
|
||||
assertThat(loggingEvent.getLevel(), is(Level.INFO));
|
||||
|
||||
assertThat(loggingEvent.getFormattedMessage(),
|
||||
is("Animal is sleeping"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() {
|
||||
|
||||
Cat cat = new Cat();
|
||||
|
||||
AnimalActivity.sleep(cat);
|
||||
|
||||
verify(mockAppender).doAppend(captorLoggingEvent.capture());
|
||||
|
||||
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
|
||||
|
||||
assertThat(loggingEvent.getLevel(), is(Level.INFO));
|
||||
|
||||
assertThat(loggingEvent.getFormattedMessage(),
|
||||
is("Cat is sleeping"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() {
|
||||
|
||||
Animal cat = new Cat();
|
||||
|
||||
AnimalActivity.sleep(cat);
|
||||
|
||||
verify(mockAppender).doAppend(captorLoggingEvent.capture());
|
||||
|
||||
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
|
||||
|
||||
assertThat(loggingEvent.getLevel(), is(Level.INFO));
|
||||
|
||||
assertThat(loggingEvent.getFormattedMessage(),
|
||||
is("Animal is sleeping"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.LoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
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 static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 01-08-2018.
|
||||
*/
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AnimalUnitTest {
|
||||
@Mock
|
||||
private Appender mockAppender;
|
||||
@Captor
|
||||
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.addAppender(mockAppender);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.detachAppender(mockAppender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalledWithoutParameters_shouldCallFunctionMakeNoiseWithoutParameters() {
|
||||
|
||||
Animal animal = new Animal();
|
||||
|
||||
animal.makeNoise();
|
||||
|
||||
verify(mockAppender).doAppend(captorLoggingEvent.capture());
|
||||
|
||||
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
|
||||
|
||||
assertThat(loggingEvent.getLevel(), is(Level.INFO));
|
||||
|
||||
assertThat(loggingEvent.getFormattedMessage(),
|
||||
is("generic animal noise"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalledWithParameters_shouldCallFunctionMakeNoiseWithParameters() {
|
||||
|
||||
Animal animal = new Animal();
|
||||
|
||||
int testValue = 3;
|
||||
animal.makeNoise(testValue);
|
||||
|
||||
verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture());
|
||||
|
||||
final List<LoggingEvent> loggingEvents = captorLoggingEvent.getAllValues();
|
||||
|
||||
for(LoggingEvent loggingEvent : loggingEvents)
|
||||
{
|
||||
assertThat(loggingEvent.getLevel(), is(Level.INFO));
|
||||
|
||||
assertThat(loggingEvent.getFormattedMessage(),
|
||||
is("generic animal noise countdown "+testValue));
|
||||
|
||||
testValue--;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.binding;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.LoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
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 static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Created by madhumita.g on 01-08-2018.
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CatUnitTest {
|
||||
|
||||
@Mock
|
||||
private Appender mockAppender;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.addAppender(mockAppender);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.detachAppender(mockAppender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void makeNoiseTest() {
|
||||
|
||||
Cat cat = new Cat();
|
||||
|
||||
cat.makeNoise();
|
||||
|
||||
verify(mockAppender).doAppend(captorLoggingEvent.capture());
|
||||
|
||||
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
|
||||
|
||||
assertThat(loggingEvent.getLevel(), is(Level.INFO));
|
||||
|
||||
assertThat(loggingEvent.getFormattedMessage(),
|
||||
is("meow"));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.modulo;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Java6Assertions.*;
|
||||
|
||||
public class ModuloUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenIntegerDivision_thenLosesRemainder(){
|
||||
assertThat(11 / 4).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDoubleDivision_thenKeepsRemainder(){
|
||||
assertThat(11 / 4.0).isEqualTo(2.75);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModulo_thenReturnsRemainder(){
|
||||
assertThat(11 % 4).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDivisionByZero_thenArithmeticException(){
|
||||
double result = 1 / 0;
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenModuloByZero_thenArithmeticException(){
|
||||
double result = 1 % 0;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){
|
||||
assertThat(3 % 2).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){
|
||||
assertThat(4 % 2).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){
|
||||
int QUEUE_CAPACITY= 10;
|
||||
int[] circularQueue = new int[QUEUE_CAPACITY];
|
||||
int itemsInserted = 0;
|
||||
for (int value = 0; value < 1000; value++) {
|
||||
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
|
||||
circularQueue[writeIndex] = value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AccountHolderManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void whenInstanciatingAccountHolder_thenThrowsException() {
|
||||
AccountHolder holder = new AccountHolder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.stackoverflowerror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CyclicDependancyManualTest {
|
||||
@Test(expected = StackOverflowError.class)
|
||||
public void whenInstanciatingClassOne_thenThrowsException() {
|
||||
ClassOne obj = new ClassOne();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.switchstatement;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import org.junit.Assert;
|
||||
|
||||
public class SwitchStatementUnitTest {
|
||||
private SwitchStatement s = new SwitchStatement();
|
||||
|
||||
|
||||
@Test
|
||||
public void whenDog_thenDomesticAnimal() {
|
||||
|
||||
String animal = "DOG";
|
||||
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoBreaks_thenGoThroughBlocks() {
|
||||
String animal = "DOG";
|
||||
Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal));
|
||||
}
|
||||
|
||||
@Test(expected=NullPointerException.class)
|
||||
public void whenSwitchAgumentIsNull_thenNullPointerException() {
|
||||
String animal = null;
|
||||
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenCompareStrings_thenByEqual() {
|
||||
String animal = new String("DOG");
|
||||
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.baeldung.synthetic;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo},
|
||||
* {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SyntheticUnitTest {
|
||||
|
||||
/**
|
||||
* Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic
|
||||
* methods.
|
||||
*/
|
||||
@Test
|
||||
public void givenSyntheticMethod_whenIsSinthetic_thenTrue() {
|
||||
// Checks that the nested class contains exactly two synthetic methods.
|
||||
Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods();
|
||||
Assert.assertEquals("This class should contain only two methods", 2, methods.length);
|
||||
|
||||
for (Method m : methods) {
|
||||
System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic());
|
||||
Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic
|
||||
* constructor.
|
||||
*/
|
||||
@Test
|
||||
public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() {
|
||||
// Checks that the nested class contains exactly a synthetic
|
||||
// constructor.
|
||||
int syntheticConstructors = 0;
|
||||
Constructor<?>[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors();
|
||||
Assert.assertEquals("This class should contain only two constructors", 2, constructors.length);
|
||||
|
||||
for (Constructor<?> c : constructors) {
|
||||
System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic());
|
||||
|
||||
// Counts the synthetic constructors.
|
||||
if (c.isSynthetic()) {
|
||||
syntheticConstructors++;
|
||||
}
|
||||
}
|
||||
|
||||
// Checks that there's exactly one synthetic constructor.
|
||||
Assert.assertEquals(1, syntheticConstructors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field.
|
||||
*/
|
||||
@Test
|
||||
public void givenSyntheticField_whenIsSinthetic_thenTrue() {
|
||||
// This class should contain exactly one synthetic field.
|
||||
Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields();
|
||||
Assert.assertEquals("This class should contain only one field", 1, fields.length);
|
||||
|
||||
for (Field f : fields) {
|
||||
System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic());
|
||||
Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that {@link BridgeMethodDemo} contains a synthetic bridge method.
|
||||
*/
|
||||
@Test
|
||||
public void givenBridgeMethod_whenIsBridge_thenTrue() {
|
||||
// This class should contain exactly one synthetic bridge method.
|
||||
int syntheticMethods = 0;
|
||||
Method[] methods = BridgeMethodDemo.class.getDeclaredMethods();
|
||||
for (Method m : methods) {
|
||||
System.out.println(
|
||||
"Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge());
|
||||
|
||||
// Counts the synthetic methods and checks that they are also bridge
|
||||
// methods.
|
||||
if (m.isSynthetic()) {
|
||||
syntheticMethods++;
|
||||
Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge());
|
||||
}
|
||||
}
|
||||
|
||||
// Checks that there's exactly one synthetic bridge method.
|
||||
Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.ternaryoperator;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TernaryOperatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() {
|
||||
int number = 10;
|
||||
String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
|
||||
|
||||
assertThat(msg).isEqualTo("Number is less than or equal to 10");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() {
|
||||
int exp1 = 0, exp2 = 0;
|
||||
int result = 12 > 10 ? ++exp1 : ++exp2;
|
||||
|
||||
assertThat(exp1).isEqualTo(1);
|
||||
assertThat(exp2).isEqualTo(0);
|
||||
assertThat(result).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() {
|
||||
int exp1 = 0, exp2 = 0;
|
||||
int result = 8 > 10 ? ++exp1 : ++exp2;
|
||||
|
||||
assertThat(exp1).isEqualTo(0);
|
||||
assertThat(exp2).isEqualTo(1);
|
||||
assertThat(result).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() {
|
||||
int number = 6;
|
||||
String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5";
|
||||
|
||||
assertThat(msg).isEqualTo("Number is greater than 5");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.throwsexception;
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user