geroza
2018-11-09 16:18:03 -02:00
parent 8e6fff4fc8
commit 792d6f6cc4
84 changed files with 583 additions and 289 deletions
@@ -1,126 +0,0 @@
package com.baeldung;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
public class PrimitiveConversionsJUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(PrimitiveConversionsJUnitTest.class);
@Test
public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() {
int myInt = 127;
long myLong = myInt;
assertEquals(127L, myLong);
float myFloat = myLong;
assertEquals(127.0f, myFloat, 0.00001f);
double myDouble = myLong;
assertEquals(127.0, myDouble,0.00001);
}
@Test
public void givenDataWithMoreBits_whenAttributingToSmallerSizeVariable_thenCastOperatorNeeded() {
long myLong = 127L;
double myDouble = 127.0;
float myFloat = (float) myDouble;
assertEquals(127.0f, myFloat, 0.00001f);
int myInt = (int) myLong;
assertEquals(127, myInt);
byte myByte = (byte) myInt;
assertEquals( ((byte)127), myByte);
}
@Test
public void givenPrimitiveData_whenAssiginingToWrapper_thenAutomaticBoxingHappens(){
int myInt = 127;
Integer myIntegerReference = myInt;
assertEquals(new Integer("127"), myIntegerReference);
}
@Test
public void givenWrapperObjectData_whenAssiginingToPrimitive_thenAutomaticUnboxingHappens(){
Integer myIntegerReference = new Integer("127");
int myOtherInt = myIntegerReference;
assertEquals(127, myOtherInt);
}
@Test
public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){
byte myLargeValueByte = (byte) 130; //0b10000010
LOG.debug("{}", myLargeValueByte); //0b10000010 -126
assertEquals( -126, myLargeValueByte);
int myLargeValueInt = myLargeValueByte;
LOG.debug("{}", myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126
assertEquals( -126, myLargeValueInt);
char myLargeValueChar = (char) myLargeValueByte;
LOG.debug("{}", myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82
assertEquals(0xFF82, myLargeValueChar);
myLargeValueInt = myLargeValueChar;
LOG.debug("{}", myLargeValueInt); //0b11111111 10000010 65410
assertEquals(65410, myLargeValueInt);
byte myOtherByte = (byte) myLargeValueInt;
LOG.debug("{}", myOtherByte); //0b10000010 -126
assertEquals( -126, myOtherByte);
char myLargeValueChar2 = 130; //This is an int not a byte!
LOG.debug("{}", myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082
assertEquals(0x0082, myLargeValueChar2);
int myLargeValueInt2 = myLargeValueChar2;
LOG.debug("{}", myLargeValueInt2); //0b00000000 10000010 130
assertEquals(130, myLargeValueInt2);
byte myOtherByte2 = (byte) myLargeValueInt2;
LOG.debug("{}", myOtherByte2); //0b10000010 -126
assertEquals( -126, myOtherByte2);
}
@Test
public void givenString_whenParsingWithWrappers_thenValuesAreReturned(){
String myString = "127";
byte myNewByte = Byte.parseByte(myString);
assertEquals( ((byte)127), myNewByte);
short myNewShort = Short.parseShort(myString);
assertEquals( ((short)127), myNewShort);
int myNewInt = Integer.parseInt(myString);
assertEquals( 127, myNewInt);
long myNewLong = Long.parseLong(myString);
assertEquals( 127L, myNewLong);
float myNewFloat = Float.parseFloat(myString);
assertEquals( 127.0f, myNewFloat, 0.00001f);
double myNewDouble = Double.parseDouble(myString);
assertEquals( 127.0, myNewDouble, 0.00001f);
boolean myNewBoolean = Boolean.parseBoolean(myString);
assertEquals( false, myNewBoolean); //numbers are not true!
char myNewChar = myString.charAt(0);
assertEquals( 49, myNewChar); //the value of '1'
}
}
@@ -1,39 +0,0 @@
package com.baeldung.breakcontinue;
import static com.baeldung.breakcontinue.BreakContinue.labeledBreak;
import static com.baeldung.breakcontinue.BreakContinue.labeledContinue;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreak;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreakNestedLoops;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledContinue;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BreakContinueUnitTest {
@Test
public void whenUnlabeledBreak_ThenEqual() {
assertEquals(4, unlabeledBreak());
}
@Test
public void whenUnlabeledBreakNestedLoops_ThenEqual() {
assertEquals(2, unlabeledBreakNestedLoops());
}
@Test
public void whenLabeledBreak_ThenEqual() {
assertEquals(1, labeledBreak());
}
@Test
public void whenUnlabeledContinue_ThenEqual() {
assertEquals(5, unlabeledContinue());
}
@Test
public void whenLabeledContinue_ThenEqual() {
assertEquals(3, labeledContinue());
}
}
@@ -1,29 +0,0 @@
package com.baeldung.comparable;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class ComparableUnitTest {
@Test
public void whenUsingComparable_thenSortedList() {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
Collections.sort(footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
}
@@ -1,47 +0,0 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class ComparatorUnitTest {
List<Player> footballTeam;
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
}
@Test
public void whenUsingRankingComparator_thenSortedList() {
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
Collections.sort(footballTeam, playerComparator);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
@Test
public void whenUsingAgeComparator_thenSortedList() {
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
Collections.sort(footballTeam, playerComparator);
assertEquals(footballTeam.get(0)
.getName(), "John");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}
@@ -1,68 +0,0 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class Java8ComparatorUnitTest {
List<Player> footballTeam;
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
}
@Test
public void whenComparing_UsingLambda_thenSorted() {
System.out.println("************** Java 8 Comaparator **************");
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
@Test
public void whenComparing_UsingComparatorComparing_thenSorted() {
System.out.println("********* Comaparator.comparing method *********");
System.out.println("********* byRanking *********");
Comparator<Player> byRanking = Comparator.comparing(Player::getRanking);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
System.out.println("********* byAge *********");
Comparator<Player> byAge = Comparator.comparing(Player::getAge);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byAge);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Roger");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}
@@ -1,57 +0,0 @@
package com.baeldung.dynamicproxy;
import org.junit.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class DynamicProxyIntegrationTest {
@Test
public void givenDynamicProxy_thenPutWorks() {
Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyIntegrationTest.class.getClassLoader(), new Class[] { Map.class }, new DynamicInvocationHandler());
proxyInstance.put("hello", "world");
}
@Test
public void givenInlineDynamicProxy_thenGetWorksOtherMethodsDoNot() {
Map proxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyIntegrationTest.class.getClassLoader(), new Class[] { Map.class }, (proxy, method, methodArgs) -> {
if (method.getName().equals("get")) {
return 42;
} else {
throw new UnsupportedOperationException("Unsupported method: " + method.getName());
}
});
int result = (int) proxyInstance.get("hello");
assertEquals(42, result);
try {
proxyInstance.put("hello", "world");
fail();
} catch(UnsupportedOperationException e) {
// expected
}
}
@Test
public void givenTimingDynamicProxy_thenMethodInvokationsProduceTiming() {
Map mapProxyInstance = (Map) Proxy.newProxyInstance(DynamicProxyIntegrationTest.class.getClassLoader(), new Class[] { Map.class }, new TimingDynamicInvocationHandler(new HashMap<>()));
mapProxyInstance.put("hello", "world");
assertEquals("world", mapProxyInstance.get("hello"));
CharSequence csProxyInstance = (CharSequence) Proxy.newProxyInstance(DynamicProxyIntegrationTest.class.getClassLoader(), new Class[] { CharSequence.class }, new TimingDynamicInvocationHandler("Hello World"));
assertEquals('l', csProxyInstance.charAt(2));
assertEquals(11, csProxyInstance.length());
}
}
@@ -1,69 +0,0 @@
package com.baeldung.generics;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
public class GenericsUnitTest {
// testing the generic method with Integer
@Test
public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<Integer> list = Generics.fromArrayToList(intArray);
assertThat(list, hasItems(intArray));
}
// testing the generic method with Integer and String type
@Test
public void givenArrayOfIntegers_thanListOfStringReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<String> stringList = Generics.fromArrayToList(intArray, Object::toString);
assertThat(stringList, hasItems("1", "2", "3", "4", "5"));
}
// testing the generic method with String
@Test
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
List<String> list = Generics.fromArrayToList(stringArray);
assertThat(list, hasItems(stringArray));
}
// testing the generic method with Number as upper bound with Integer
// if we test fromArrayToListWithUpperBound with any type that doesn't
// extend Number it will fail to compile
@Test
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
assertThat(list, hasItems(intArray));
}
// testing paintAllBuildings method with a subtype of Building, the method
// will work with all subtypes of Building
@Test
public void givenSubTypeOfWildCardBoundedGenericType_thanPaintingOK() {
try {
List<Building> subBuildingsList = new ArrayList<>();
subBuildingsList.add(new Building());
subBuildingsList.add(new House());
// prints
// Painting Building
// Painting House
Generics.paintAllBuildings(subBuildingsList);
} catch (Exception e) {
fail();
}
}
}
@@ -1,26 +0,0 @@
package com.baeldung.hashcode.application;
import com.baeldung.hashcode.entities.User;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertTrue;
public class ApplicationUnitTest {
@Test
public void main_NoInputState_TextPrintedToConsole() throws Exception {
Map<User, User> users = new HashMap<>();
User user1 = new User(1L, "John", "john@domain.com");
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
User user3 = new User(3L, "Mary", "mary@domain.com");
users.put(user1, user1);
users.put(user2, user2);
users.put(user3, user3);
assertTrue(users.containsKey(user1));
}
}
@@ -1,34 +0,0 @@
package com.baeldung.hashcode.entities;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class UserUnitTest {
private User user;
private User comparisonUser;
@Before
public void setUpUserInstances() {
this.user = new User(1L, "test", "test@domain.com");
this.comparisonUser = this.user;
}
@After
public void tearDownUserInstances() {
user = null;
comparisonUser = null;
}
@Test
public void equals_EqualUserInstance_TrueAssertion() {
Assert.assertTrue(user.equals(comparisonUser));
}
@Test
public void hashCode_UserHash_TrueAssertion() {
Assert.assertEquals(1792276941, user.hashCode());
}
}
@@ -1,37 +0,0 @@
package com.baeldung.initializationguide;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import java.lang.reflect.InvocationTargetException;
public class UserUnitTest {
@Test
public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() {
User user = new User("Alice", 1);
assertThat(user).isNotNull();
}
@Test
public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
User user = User.class.getConstructor(String.class, int.class)
.newInstance("Alice", 2);
assertThat(user).isNotNull();
}
@Test
public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException {
User user = new User("Alice", 3);
User clonedUser = (User) user.clone();
assertThat(clonedUser).isEqualTo(user);
}
@Test
public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() {
User user = new User();
assertThat(user.getName()).isNull();
assertThat(user.getId() == 0);
}
}
@@ -1,46 +0,0 @@
package com.baeldung.java.doublebrace;
import org.junit.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertTrue;
public class DoubleBraceUnitTest {
@Test
public void whenInitializeSetWithoutDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<>();
countries.add("India");
countries.add("USSR");
countries.add("USA");
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeSetWithDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<String>() {
{
add("India");
add("USSR");
add("USA");
}
};
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
Set<String> countries = Stream.of("India", "USSR", "USA")
.collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
assertTrue(countries.contains("India"));
}
}
@@ -1,57 +0,0 @@
package com.baeldung.java.reflection;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
public class OperationsUnitTest {
public OperationsUnitTest() {
}
@Test(expected = IllegalAccessException.class)
public void givenObject_whenInvokePrivateMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method andPrivateMethod = Operations.class.getDeclaredMethod("privateAnd", boolean.class, boolean.class);
Operations operationsInstance = new Operations();
Boolean result = (Boolean) andPrivateMethod.invoke(operationsInstance, true, false);
assertFalse(result);
}
@Test
public void givenObject_whenInvokePrivateMethod_thenCorrect() throws Exception {
Method andPrivatedMethod = Operations.class.getDeclaredMethod("privateAnd", boolean.class, boolean.class);
andPrivatedMethod.setAccessible(true);
Operations operationsInstance = new Operations();
Boolean result = (Boolean) andPrivatedMethod.invoke(operationsInstance, true, false);
assertFalse(result);
}
@Test
public void givenObject_whenInvokePublicMethod_thenCorrect() throws Exception {
Method sumInstanceMethod = Operations.class.getMethod("publicSum", int.class, double.class);
Operations operationsInstance = new Operations();
Double result = (Double) sumInstanceMethod.invoke(operationsInstance, 1, 3);
assertThat(result, equalTo(4.0));
}
@Test
public void givenObject_whenInvokeStaticMethod_thenCorrect() throws Exception {
Method multiplyStaticMethod = Operations.class.getDeclaredMethod("publicStaticMultiply", float.class, long.class);
Double result = (Double) multiplyStaticMethod.invoke(null, 3.5f, 2);
assertThat(result, equalTo(7.0));
}
}
@@ -1,302 +0,0 @@
package com.baeldung.java.reflection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class ReflectionUnitTest {
@Test
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
final Object person = new Person();
final Field[] fields = person.getClass().getDeclaredFields();
final List<String> actualFieldNames = getFieldNames(fields);
assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames));
}
@Test
public void givenObject_whenGetsClassName_thenCorrect() {
final Object goat = new Goat("goat");
final Class<?> clazz = goat.getClass();
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
}
@Test
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
final Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
}
@Test
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final int goatMods = goatClass.getModifiers();
final int animalMods = animalClass.getModifiers();
assertTrue(Modifier.isPublic(goatMods));
assertTrue(Modifier.isAbstract(animalMods));
assertTrue(Modifier.isPublic(animalMods));
}
@Test
public void givenClass_whenGetsPackageInfo_thenCorrect() {
final Goat goat = new Goat("goat");
final Class<?> goatClass = goat.getClass();
final Package pkg = goatClass.getPackage();
assertEquals("com.baeldung.java.reflection", pkg.getName());
}
@Test
public void givenClass_whenGetsSuperClass_thenCorrect() {
final Goat goat = new Goat("goat");
final String str = "any string";
final Class<?> goatClass = goat.getClass();
final Class<?> goatSuperClass = goatClass.getSuperclass();
assertEquals("Animal", goatSuperClass.getSimpleName());
assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
}
@Test
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Class<?>[] goatInterfaces = goatClass.getInterfaces();
final Class<?>[] animalInterfaces = animalClass.getInterfaces();
assertEquals(1, goatInterfaces.length);
assertEquals(1, animalInterfaces.length);
assertEquals("Locomotion", goatInterfaces[0].getSimpleName());
assertEquals("Eating", animalInterfaces[0].getSimpleName());
}
@Test
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Constructor<?>[] constructors = goatClass.getConstructors();
assertEquals(1, constructors.length);
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
}
@Test
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Field[] fields = animalClass.getDeclaredFields();
final List<String> actualFields = getFieldNames(fields);
assertEquals(2, actualFields.size());
assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
}
@Test
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Method[] methods = animalClass.getDeclaredMethods();
final List<String> actualMethods = getMethodNames(methods);
assertEquals(3, actualMethods.size());
assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound")));
}
@Test
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Constructor<?>[] constructors = birdClass.getConstructors();
assertEquals(3, constructors.length);
}
@Test
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
birdClass.getConstructor();
birdClass.getConstructor(String.class);
birdClass.getConstructor(String.class, boolean.class);
}
@Test
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Constructor<?> cons1 = birdClass.getConstructor();
final Constructor<?> cons2 = birdClass.getConstructor(String.class);
final Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
final Bird bird1 = (Bird) cons1.newInstance();
final Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
final Bird bird3 = (Bird) cons3.newInstance("dove", true);
assertEquals("bird", bird1.getName());
assertEquals("Weaver bird", bird2.getName());
assertEquals("dove", bird3.getName());
assertFalse(bird1.walks());
assertTrue(bird3.walks());
}
@Test
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field[] fields = birdClass.getFields();
assertEquals(1, fields.length);
assertEquals("CATEGORY", fields[0].getName());
}
@Test
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getField("CATEGORY");
assertEquals("CATEGORY", field.getName());
}
@Test
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field[] fields = birdClass.getDeclaredFields();
assertEquals(1, fields.length);
assertEquals("walks", fields[0].getName());
}
@Test
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getDeclaredField("walks");
assertEquals("walks", field.getName());
}
@Test
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
final Class<?> fieldClass = field.getType();
assertEquals("boolean", fieldClass.getSimpleName());
}
@Test
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Bird bird = (Bird) birdClass.newInstance();
final Field field = birdClass.getDeclaredField("walks");
field.setAccessible(true);
assertFalse(field.getBoolean(bird));
assertFalse(bird.walks());
field.set(bird, true);
assertTrue(field.getBoolean(bird));
assertTrue(bird.walks());
}
@Test
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getField("CATEGORY");
field.setAccessible(true);
assertEquals("domestic", field.get(null));
}
@Test
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Method[] methods = birdClass.getMethods();
final List<String> methodNames = getMethodNames(methods);
assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString")));
}
@Test
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
assertEquals(expectedMethodNames.size(), actualMethodNames.size());
assertTrue(expectedMethodNames.containsAll(actualMethodNames));
assertTrue(actualMethodNames.containsAll(expectedMethodNames));
}
@Test
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Method walksMethod = birdClass.getDeclaredMethod("walks");
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
assertFalse(walksMethod.isAccessible());
assertFalse(setWalksMethod.isAccessible());
walksMethod.setAccessible(true);
setWalksMethod.setAccessible(true);
assertTrue(walksMethod.isAccessible());
assertTrue(setWalksMethod.isAccessible());
}
@Test
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Bird bird = (Bird) birdClass.newInstance();
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
final Method walksMethod = birdClass.getDeclaredMethod("walks");
final boolean walks = (boolean) walksMethod.invoke(bird);
assertFalse(walks);
assertFalse(bird.walks());
setWalksMethod.invoke(bird, true);
final boolean walks2 = (boolean) walksMethod.invoke(bird);
assertTrue(walks2);
assertTrue(bird.walks());
}
private static List<String> getFieldNames(Field[] fields) {
final List<String> fieldNames = new ArrayList<>();
for (final Field field : fields) {
fieldNames.add(field.getName());
}
return fieldNames;
}
private static List<String> getMethodNames(Method[] methods) {
final List<String> methodNames = new ArrayList<>();
for (final Method method : methods) {
methodNames.add(method.getName());
}
return methodNames;
}
}
@@ -1,38 +0,0 @@
package com.baeldung.java.reflection.operations;
import com.baeldung.java.reflection.*;
import static org.hamcrest.CoreMatchers.equalTo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
import static org.junit.Assert.assertThat;
public class MoreOperationsUnitTest {
public MoreOperationsUnitTest() {
}
@Test(expected = IllegalAccessException.class)
public void givenObject_whenInvokeProtectedMethod_thenFail() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method maxProtectedMethod = Operations.class.getDeclaredMethod("protectedMax", int.class, int.class);
Operations operationsInstance = new Operations();
Integer result = (Integer) maxProtectedMethod.invoke(operationsInstance, 2, 4);
assertThat(result, equalTo(4));
}
@Test
public void givenObject_whenInvokeProtectedMethod_thenCorrect() throws Exception {
Method maxProtectedMethod = Operations.class.getDeclaredMethod("protectedMax", int.class, int.class);
maxProtectedMethod.setAccessible(true);
Operations operationsInstance = new Operations();
Integer result = (Integer) maxProtectedMethod.invoke(operationsInstance, 2, 4);
assertThat(result, equalTo(4));
}
}
@@ -1,107 +0,0 @@
package com.baeldung.loops;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class WhenUsingLoops {
private LoopsInJava loops = new LoopsInJava();
private static List<String> list = new ArrayList<>();
private static Set<String> set = new HashSet<>();
private static Map<String, Integer> map = new HashMap<>();
@BeforeClass
public static void setUp() {
list.add("One");
list.add("Two");
list.add("Three");
set.add("Four");
set.add("Five");
set.add("Six");
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
}
@Test
public void shouldRunForLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.simple_for_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunEnhancedForeachLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.enhanced_for_each_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunWhileLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunDoWhileLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.do_while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void whenUsingSimpleFor_shouldIterateList() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateList() {
for (String item : list) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateSet() {
for (String item : set) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateMap() {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
}
}
@Test
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
aa: for (int i = 1; i <= 3; i++) {
if (i == 1)
continue;
bb: for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break aa;
}
System.out.println(i + " " + j);
}
}
}
}
@@ -1,20 +0,0 @@
package com.baeldung.nestedclass;
import org.junit.Test;
abstract class SimpleAbstractClass {
abstract void run();
}
public class AnonymousInner {
@Test
public void run() {
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
void run() {
System.out.println("Running Anonymous Class...");
}
};
simpleAbstractClass.run();
}
}
@@ -1,21 +0,0 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Enclosing {
private static int x = 1;
public static class StaticNested {
private void run() {
System.out.println("x = " + x);
}
}
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
nested.run();
}
}
@@ -1,22 +0,0 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewEnclosing {
private void run() {
class Local {
void run() {
System.out.println("Welcome to Baeldung!");
}
}
Local local = new Local();
local.run();
}
@Test
public void test() {
NewEnclosing newEnclosing = new NewEnclosing();
newEnclosing.run();
}
}
@@ -1,30 +0,0 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewOuter {
int a = 1;
static int b = 2;
public class InnerClass {
int a = 3;
static final int b = 4;
public void run() {
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("NewOuter.this.a = " + NewOuter.this.a);
System.out.println("NewOuter.b = " + NewOuter.b);
System.out.println("NewOuter.this.b = " + NewOuter.this.b);
}
}
@Test
public void test() {
NewOuter outer = new NewOuter();
NewOuter.InnerClass inner = outer.new InnerClass();
inner.run();
}
}
@@ -1,20 +0,0 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Outer {
public class Inner {
public void run() {
System.out.println("Calling test...");
}
}
@Test
public void test() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.run();
}
}
@@ -1,14 +0,0 @@
package com.baeldung.staticdemo;
import static org.junit.Assert.*;
import org.junit.Test;
public class CarIntegrationTest {
@Test
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
new Car("Jaguar", "V8");
new Car("Bugatti", "W16");
assertEquals(2, Car.numberOfCars);
}
}
@@ -1,15 +0,0 @@
package com.baeldung.staticdemo;
import org.junit.Assert;
import org.junit.Test;
public class SingletonIntegrationTest {
@Test
public void givenStaticInnerClass_whenMultipleTimesInstanceCalled_thenOnlyOneTimeInitialized() {
Singleton object1 = Singleton.getInstance();
Singleton object2 = Singleton.getInstance();
Assert.assertSame(object1, object2);
}
}
@@ -1,17 +0,0 @@
package com.baeldung.staticdemo;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
public class StaticBlockIntegrationTest {
@Test
public void whenAddedListElementsThroughStaticBlock_thenEnsureCorrectOrder() {
List<String> actualList = StaticBlock.getRanks();
assertThat(actualList, contains("Lieutenant", "Captain", "Major", "Colonel", "General"));
}
}
@@ -1,60 +0,0 @@
package com.baeldung.varargs;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class FormatterUnitTest {
private final static String FORMAT = "%s %s %s";
@Test
public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() {
String actualResult = format();
assertThat(actualResult, is("empty "));
}
@Test
public void givenOneArgument_thenResultHasTwoTrailingSpace() {
String actualResult = format("baeldung");
assertThat(actualResult, is("baeldung "));
}
@Test
public void givenTwoArguments_thenOneTrailingSpaceExists() {
String actualResult = format("baeldung", "rocks");
assertThat(actualResult, is("baeldung rocks "));
}
@Test
public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() {
String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring");
assertThat(actualResult, is("baeldung rocks java"));
}
public String format() {
return format("empty", "");
}
public String format(String value) {
return format(value, "");
}
public String format(String val1, String val2) {
return String.format(FORMAT, val1, val2, "");
}
public String formatWithVarArgs(String... values) {
if (values.length == 0) {
return "no arguments given";
}
return String.format(FORMAT, values);
}
}
@@ -1,35 +0,0 @@
package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.equalshashcode.entities.ComplexClass;
public class ComplexClassUnitTest {
@Test
public void testEqualsAndHashcodes() {
List<String> strArrayList = new ArrayList<String>();
strArrayList.add("abc");
strArrayList.add("def");
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
ComplexClass bObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
List<String> strArrayListD = new ArrayList<String>();
strArrayListD.add("lmn");
strArrayListD.add("pqr");
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}
@@ -1,25 +0,0 @@
package org.baeldung.equalshashcode.entities;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.equalshashcode.entities.PrimitiveClass;
public class PrimitiveClassUnitTest {
@Test
public void testTwoEqualsObjects() {
PrimitiveClass aObject = new PrimitiveClass(false, 2);
PrimitiveClass bObject = new PrimitiveClass(false, 2);
PrimitiveClass dObject = new PrimitiveClass(true, 2);
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}
@@ -1,27 +0,0 @@
package org.baeldung.equalshashcode.entities;
import java.awt.Color;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.equalshashcode.entities.Square;
public class SquareClassUnitTest {
@Test
public void testEqualsAndHashcodes() {
Square aObject = new Square(10, Color.BLUE);
Square bObject = new Square(10, Color.BLUE);
Square dObject = new Square(20, Color.BLUE);
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}
@@ -1,5 +0,0 @@
package org.baeldung.java.diamond;
public class Car<T extends Engine> implements Vehicle<T> {
}
@@ -1,13 +0,0 @@
package org.baeldung.java.diamond;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class DiamondOperatorUnitTest {
@Test
public void whenCreateCarUsingDiamondOperator_thenSuccess() {
Car<Diesel> myCar = new Car<>();
assertNotNull(myCar);
}
}
@@ -1,10 +0,0 @@
package org.baeldung.java.diamond;
public class Diesel implements Engine {
@Override
public void start() {
System.out.println("Started Diesel...");
}
}
@@ -1,6 +0,0 @@
package org.baeldung.java.diamond;
public interface Engine {
void start();
}
@@ -1,5 +0,0 @@
package org.baeldung.java.diamond;
public interface Vehicle<T extends Engine> {
}