[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

View File

@@ -0,0 +1,80 @@
package com.baeldung.casting;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
public class CastingUnitTest {
@Test
public void whenPrimitiveConverted_thenValueChanged() {
double myDouble = 1.1;
int myInt = (int) myDouble;
assertNotEquals(myDouble, myInt);
}
@Test
public void whenUpcast_thenInstanceUnchanged() {
Cat cat = new Cat();
Animal animal = cat;
animal = (Animal) cat;
assertTrue(animal instanceof Cat);
}
@Test
public void whenUpcastToObject_thenInstanceUnchanged() {
Object object = new Animal();
assertTrue(object instanceof Animal);
}
@Test
public void whenUpcastToInterface_thenInstanceUnchanged() {
Mew mew = new Cat();
assertTrue(mew instanceof Cat);
}
@Test
public void whenUpcastToAnimal_thenOverridenMethodsCalled() {
List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
new AnimalFeeder().feed(animals);
}
@Test
public void whenDowncastToCat_thenMeowIsCalled() {
Animal animal = new Cat();
((Cat) animal).meow();
}
@Test(expected = ClassCastException.class)
public void whenDownCastWithoutCheck_thenExceptionThrown() {
List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
new AnimalFeeder().uncheckedFeed(animals);
}
@Test
public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() {
Animal animal = new Cat();
if (Cat.class.isInstance(animal)) {
Cat cat = Cat.class.cast(animal);
cat.meow();
}
}
@Test
public void whenParameterCat_thenOnlyCatsFed() {
List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
AnimalFeederGeneric<Cat> catFeeder = new AnimalFeederGeneric<Cat>(Cat.class);
List<Cat> fedAnimals = catFeeder.feed(animals);
assertTrue(fedAnimals.size() == 1);
assertTrue(fedAnimals.get(0) instanceof Cat);
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.constructors;
import com.baeldung.constructors.*;
import java.util.logging.Logger;
import java.time.LocalDateTime;
import java.time.Month;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ConstructorUnitTest {
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
@Test
public void givenNoExplicitContructor_whenUsed_thenFails() {
BankAccount account = new BankAccount();
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
}
@Test
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
}
@Test
public void givenParameterisedConstructor_whenUsed_thenSucceeds() {
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
BankAccountParameterizedConstructor account =
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
}
@Test
public void givenCopyContructor_whenUser_thenMaintainsLogic() {
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
BankAccountCopyConstructor account = new BankAccountCopyConstructor("Tim", opened, 1000.0f);
BankAccountCopyConstructor newAccount = new BankAccountCopyConstructor(account);
assertThat(account.getName()).isEqualTo(newAccount.getName());
assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
}
}

View File

@@ -0,0 +1,128 @@
package com.baeldung.deepcopy;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Ignore;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
public class DeepCopyUnitTest {
@Test
public void whenCreatingDeepCopyWithCopyConstructor_thenObjectsShouldNotBeSame() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User deepCopy = new User(pm);
assertThat(deepCopy).isNotSameAs(pm);
}
@Test
public void whenModifyingOriginalObject_thenConstructorCopyShouldNotChange() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User deepCopy = new User(pm);
address.setCountry("Great Britain");
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
}
@Test
public void whenModifyingOriginalObject_thenCloneCopyShouldNotChange() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User deepCopy = (User) pm.clone();
address.setCountry("Great Britain");
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
}
@Test
public void whenModifyingOriginalObject_thenCommonsCloneShouldNotChange() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User deepCopy = (User) SerializationUtils.clone(pm);
address.setCountry("Great Britain");
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
}
@Test
public void whenModifyingOriginalObject_thenGsonCloneShouldNotChange() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
Gson gson = new Gson();
User deepCopy = gson.fromJson(gson.toJson(pm), User.class);
address.setCountry("Great Britain");
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
}
@Test
public void whenModifyingOriginalObject_thenJacksonCopyShouldNotChange() throws IOException {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
ObjectMapper objectMapper = new ObjectMapper();
User deepCopy = objectMapper.readValue(objectMapper.writeValueAsString(pm), User.class);
address.setCountry("Great Britain");
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
}
@Test
@Ignore
public void whenMakingCopies_thenShowHowLongEachMethodTakes() throws CloneNotSupportedException, IOException {
int times = 1000000;
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
long start = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
User primeMinisterClone = (User) SerializationUtils.clone(pm);
}
long end = System.currentTimeMillis();
System.out.println("Cloning with Apache Commons Lang took " + (end - start) + " milliseconds.");
start = System.currentTimeMillis();
Gson gson = new Gson();
for (int i = 0; i < times; i++) {
User primeMinisterClone = gson.fromJson(gson.toJson(pm), User.class);
}
end = System.currentTimeMillis();
System.out.println("Cloning with Gson took " + (end - start) + " milliseconds.");
start = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
User primeMinisterClone = new User(pm);
}
end = System.currentTimeMillis();
System.out.println("Cloning with the copy constructor took " + (end - start) + " milliseconds.");
start = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
User primeMinisterClone = (User) pm.clone();
}
end = System.currentTimeMillis();
System.out.println("Cloning with Cloneable interface took " + (end - start) + " milliseconds.");
start = System.currentTimeMillis();
ObjectMapper objectMapper = new ObjectMapper();
for (int i = 0; i < times; i++) {
User primeMinisterClone = objectMapper.readValue(objectMapper.writeValueAsString(pm), User.class);
}
end = System.currentTimeMillis();
System.out.println("Cloning with Jackson took " + (end - start) + " milliseconds.");
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.deepcopy;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ShallowCopyUnitTest {
@Test
public void whenShallowCopying_thenObjectsShouldNotBeSame() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User shallowCopy = new User(pm.getFirstName(), pm.getLastName(), pm.getAddress());
assertThat(shallowCopy)
.isNotSameAs(pm);
}
@Test
public void whenModifyingOriginalObject_thenCopyShouldChange() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User shallowCopy = new User(pm.getFirstName(), pm.getLastName(), pm.getAddress());
address.setCountry("Great Britain");
assertThat(shallowCopy.getAddress().getCountry())
.isEqualTo(pm.getAddress().getCountry());
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.equalshashcode;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class MoneyUnitTest {
@Test
public void givenMoneyInstancesWithSameAmountAndCurrency_whenEquals_thenReturnsTrue() {
Money income = new Money(55, "USD");
Money expenses = new Money(55, "USD");
assertTrue(income.equals(expenses));
}
@Test
public void givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() {
Money cash = new Money(42, "USD");
WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon");
assertFalse(voucher.equals(cash));
assertTrue(cash.equals(voucher));
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.equalshashcode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
public class TeamUnitTest {
@Test
public void givenMapKeyWithHashCode_whenSearched_thenReturnsCorrectValue() {
Map<Team,String> leaders = new HashMap<>();
leaders.put(new Team("New York", "development"), "Anne");
leaders.put(new Team("Boston", "development"), "Brian");
leaders.put(new Team("Boston", "marketing"), "Charlie");
Team myTeam = new Team("New York", "development");
String myTeamleader = leaders.get(myTeam);
assertEquals("Anne", myTeamleader);
}
@Test
public void givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue() {
Map<WrongTeam,String> leaders = new HashMap<>();
leaders.put(new WrongTeam("New York", "development"), "Anne");
leaders.put(new WrongTeam("Boston", "development"), "Brian");
leaders.put(new WrongTeam("Boston", "marketing"), "Charlie");
WrongTeam myTeam = new WrongTeam("New York", "development");
String myTeamleader = leaders.get(myTeam);
assertFalse("Anne".equals(myTeamleader));
}
@Test
public void equalsContract() {
EqualsVerifier.forClass(Team.class).verify();
}
}

View File

@@ -0,0 +1,35 @@
package com.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());
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.equalshashcode.entities;
import org.junit.Assert;
import org.junit.Test;
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());
}
}

View File

@@ -0,0 +1,27 @@
package com.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());
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.finalkeyword;
import org.junit.Test;
import static org.junit.Assert.*;
public class FinalUnitTest {
@Test
public void whenChangedFinalClassProperties_thenChanged() {
Cat cat = new Cat();
cat.setWeight(1);
assertEquals(1, cat.getWeight());
}
@Test
public void whenFinalVariableAssign_thenOnlyOnce() {
final int i;
i = 1;
// i=2;
}
@Test
public void whenChangedFinalReference_thenChanged() {
final Cat cat = new Cat();
// cat=new Cat();
cat.setWeight(5);
assertEquals(5, cat.getWeight());
}
}

View File

@@ -0,0 +1,26 @@
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));
}
}

View File

@@ -0,0 +1,34 @@
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());
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.immutableobjects;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class ImmutableObjectsUnitTest {
@Test
public void whenCallingStringReplace_thenStringDoesNotMutate() {
// 2. What's an Immutable Object?
final String name = "baeldung";
final String newName = name.replace("dung", "----");
assertEquals("baeldung", name);
assertEquals("bael----", newName);
}
public void whenReassignFinalValue_thenCompilerError() {
// 3. The final Keyword in Java (1)
final String name = "baeldung";
// name = "bael...";
}
@Test
public void whenAddingElementToList_thenSizeChange() {
// 3. The final Keyword in Java (2)
final List<String> strings = new ArrayList<>();
assertEquals(0, strings.size());
strings.add("baeldung");
assertEquals(1, strings.size());
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.inheritance;
import com.baeldung.inheritance.*;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AppUnitTest extends TestCase {
public AppUnitTest(String testName) {
super( testName );
}
public static Test suite() {
return new TestSuite(AppUnitTest.class);
}
@SuppressWarnings("static-access")
public void testStaticMethodUsingBaseClassVariable() {
Car first = new ArmoredCar();
assertEquals("Car", first.msg());
}
@SuppressWarnings("static-access")
public void testStaticMethodUsingDerivedClassVariable() {
ArmoredCar second = new ArmoredCar();
assertEquals("ArmoredCar", second.msg());
}
public void testAssignArmoredCarToCar() {
Employee e1 = new Employee("Shreya", new ArmoredCar());
assertNotNull(e1.getCar());
}
public void testAssignSpaceCarToCar() {
Employee e2 = new Employee("Paul", new SpaceCar());
assertNotNull(e2.getCar());
}
public void testBMWToCar() {
Employee e3 = new Employee("Pavni", new BMW());
assertNotNull(e3.getCar());
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Actress;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class ActressUnitTest {
private static Actress actress;
@BeforeClass
public static void setUpActressInstance() {
actress = new Actress("Susan", "susan@domain.com", 30);
}
@Test
public void givenActressInstance_whenCalledgetName_thenEqual() {
assertThat(actress.getName()).isEqualTo("Susan");
}
@Test
public void givenActressInstance_whenCalledgetEmail_thenEqual() {
assertThat(actress.getEmail()).isEqualTo("susan@domain.com");
}
@Test
public void givenActressInstance_whenCalledgetAge_thenEqual() {
assertThat(actress.getAge()).isEqualTo(30);
}
@Test
public void givenActressInstance_whenCalledreadScript_thenEqual() {
assertThat(actress.readScript("Psycho")).isEqualTo("Reading the script of Psycho");
}
@Test
public void givenActressInstance_whenCalledperfomRole_thenEqual() {
assertThat(actress.performRole()).isEqualTo("Performing a role");
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Computer;
import com.baeldung.inheritancecomposition.model.Memory;
import com.baeldung.inheritancecomposition.model.Processor;
import com.baeldung.inheritancecomposition.model.StandardMemory;
import com.baeldung.inheritancecomposition.model.StandardProcessor;
import com.baeldung.inheritancecomposition.model.StandardSoundCard;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class CompositionUnitTest {
@Test
public void givenComputerInstance_whenExtractedEachField_thenThreeAssertions() {
Computer computer = new Computer(new StandardProcessor("Intel I3"), new StandardMemory("Kingston", "1TB"));
computer.setSoundCard(new StandardSoundCard("Generic Sound Card"));
assertThat(computer.getProcessor()).isInstanceOf(Processor.class);
assertThat(computer.getMemory()).isInstanceOf(Memory.class);
assertThat(computer.getSoundCard()).isInstanceOf(Optional.class);
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Actress;
import com.baeldung.inheritancecomposition.model.Person;
import com.baeldung.inheritancecomposition.model.Waitress;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class InheritanceUnitTest {
@Test
public void givenWaitressInstance_whenCheckedType_thenIsInstanceOfPerson() {
assertThat(new Waitress("Mary", "mary@domain.com", 22)).isInstanceOf(Person.class);
}
@Test
public void givenActressInstance_whenCheckedType_thenIsInstanceOfPerson() {
assertThat(new Actress("Susan", "susan@domain.com", 30)).isInstanceOf(Person.class);
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Person;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class PersonUnitTest {
private static Person person;
@BeforeClass
public static void setPersonInstance() {
person = new Person("John", "john@domain.com", 35);
}
@Test
public void givenPersonInstance_whenCalledgetName_thenEqual() {
assertThat(person.getName()).isEqualTo("John");
}
@Test
public void givenPersonInstance_whenCalledgetEmail_thenEqual() {
assertThat(person.getEmail()).isEqualTo("john@domain.com");
}
@Test
public void givenPersonInstance_whenCalledgetAge_thenEqual() {
assertThat(person.getAge()).isEqualTo(35);
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Waitress;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class WaitressUnitTest {
private static Waitress waitress;
@BeforeClass
public static void setUpWaitressInstance() {
waitress = new Waitress("Mary", "mary@domain.com", 22);
}
@Test
public void givenWaitressInstance_whenCalledgetName_thenOneAssertion() {
assertThat(waitress.getName()).isEqualTo("Mary");
}
@Test
public void givenWaitressInstance_whenCalledgetEmail_thenOneAssertion() {
assertThat(waitress.getEmail()).isEqualTo("mary@domain.com");
}
@Test
public void givenWaitressInstance_whenCalledgetAge_thenOneAssertion() {
assertThat(waitress.getAge()).isEqualTo(22);
}
@Test
public void givenWaitressInstance_whenCalledserveStarter_thenOneAssertion() {
assertThat(waitress.serveStarter("mixed salad")).isEqualTo("Serving a mixed salad");
}
@Test
public void givenWaitressInstance_whenCalledserveMainCourse_thenOneAssertion() {
assertThat(waitress.serveMainCourse("steak")).isEqualTo("Serving a steak");
}
@Test
public void givenWaitressInstance_whenCalledserveDessert_thenOneAssertion() {
assertThat(waitress.serveDessert("cup of coffee")).isEqualTo("Serving a cup of coffee");
}
}

View File

@@ -0,0 +1,37 @@
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);
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.markerinterface;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class MarkerInterfaceUnitTest {
@Test
public void givenDeletableObjectThenTrueReturned() {
ShapeDao shapeDao = new ShapeDao();
Object rectangle = new Rectangle(2, 3);
boolean result = shapeDao.delete(rectangle);
assertEquals(true, result);
}
@Test
public void givenNonDeletableObjectThenFalseReturned() {
ShapeDao shapeDao = new ShapeDao();
Object object = new Object();
boolean result = shapeDao.delete(object);
assertEquals(false, result);
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.methodoverloadingoverriding.test;
import com.baeldung.methodoverloadingoverriding.util.Multiplier;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class MethodOverloadingUnitTest {
private static Multiplier multiplier;
@BeforeClass
public static void setUpMultiplierInstance() {
multiplier = new Multiplier();
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithTwoIntegers_thenOneAssertion() {
assertThat(multiplier.multiply(10, 10)).isEqualTo(100);
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithTreeIntegers_thenOneAssertion() {
assertThat(multiplier.multiply(10, 10, 10)).isEqualTo(1000);
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithIntDouble_thenOneAssertion() {
assertThat(multiplier.multiply(10, 10.5)).isEqualTo(105.0);
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithDoubleDouble_thenOneAssertion() {
assertThat(multiplier.multiply(10.5, 10.5)).isEqualTo(110.25);
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithIntIntAndMatching_thenNoTypePromotion() {
assertThat(multiplier.multiply(10, 10)).isEqualTo(100);
}
}

View File

@@ -0,0 +1,68 @@
package com.baeldung.methodoverloadingoverriding.test;
import com.baeldung.methodoverloadingoverriding.model.Car;
import com.baeldung.methodoverloadingoverriding.model.Vehicle;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class MethodOverridingUnitTest {
private static Vehicle vehicle;
private static Car car;
@BeforeClass
public static void setUpVehicleInstance() {
vehicle = new Vehicle();
}
@BeforeClass
public static void setUpCarInstance() {
car = new Car();
}
@Test
public void givenVehicleInstance_whenCalledAccelerate_thenOneAssertion() {
assertThat(vehicle.accelerate(100)).isEqualTo("The vehicle accelerates at : 100 MPH.");
}
@Test
public void givenVehicleInstance_whenCalledRun_thenOneAssertion() {
assertThat(vehicle.run()).isEqualTo("The vehicle is running.");
}
@Test
public void givenVehicleInstance_whenCalledStop_thenOneAssertion() {
assertThat(vehicle.stop()).isEqualTo("The vehicle has stopped.");
}
@Test
public void givenCarInstance_whenCalledAccelerate_thenOneAssertion() {
assertThat(car.accelerate(80)).isEqualTo("The car accelerates at : 80 MPH.");
}
@Test
public void givenCarInstance_whenCalledRun_thenOneAssertion() {
assertThat(car.run()).isEqualTo("The vehicle is running.");
}
@Test
public void givenCarInstance_whenCalledStop_thenOneAssertion() {
assertThat(car.stop()).isEqualTo("The vehicle has stopped.");
}
@Test
public void givenVehicleCarInstances_whenCalledAccelerateWithSameArgument_thenNotEqual() {
assertThat(vehicle.accelerate(100)).isNotEqualTo(car.accelerate(100));
}
@Test
public void givenVehicleCarInstances_whenCalledRun_thenEqual() {
assertThat(vehicle.run()).isEqualTo(car.run());
}
@Test
public void givenVehicleCarInstances_whenCalledStop_thenEqual() {
assertThat(vehicle.stop()).isEqualTo(car.stop());
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.parameterpassing;
import org.junit.Assert;
import org.junit.Test;
public class NonPrimitivesUnitTest {
@Test
public void whenModifyingObjects_thenOriginalObjectChanged() {
Foo a = new Foo(1);
Foo b = new Foo(1);
// Before Modification
Assert.assertEquals(a.num, 1);
Assert.assertEquals(b.num, 1);
modify(a, b);
// After Modification
Assert.assertEquals(a.num, 2);
Assert.assertEquals(b.num, 1);
}
public static void modify(Foo a1, Foo b1) {
a1.num++;
b1 = new Foo(1);
b1.num++;
}
}
class Foo {
public int num;
public Foo(int num) {
this.num = num;
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.parameterpassing;
import org.junit.Assert;
import org.junit.Test;
public class PrimitivesUnitTest {
@Test
public void whenModifyingPrimitives_thenOriginalValuesNotModified() {
int x = 1;
int y = 2;
// Before Modification
Assert.assertEquals(x, 1);
Assert.assertEquals(y, 2);
modify(x, y);
// After Modification
Assert.assertEquals(x, 1);
Assert.assertEquals(y, 2);
}
public static void modify(int x1, int y1) {
x1 = 5;
y1 = 10;
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.polymorphism;
import static org.junit.Assert.*;
import java.awt.image.BufferedImage;
import org.junit.Test;
public class PolymorphismUnitTest {
@Test
public void givenImageFile_whenFileCreated_shouldSucceed() {
ImageFile imageFile = FileManager.createImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
.getBytes(), "v1.0.0");
assertEquals(200, imageFile.getHeight());
}
// Downcasting then Upcasting
@Test
public void givenTextFile_whenTextFileCreatedAndAssignedToGenericFileAndCastBackToTextFileOnGetWordCount_shouldSucceed() {
GenericFile textFile = FileManager.createTextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
TextFile textFile2 = (TextFile) textFile;
assertEquals(6, textFile2.getWordCount());
}
// Downcasting
@Test(expected = ClassCastException.class)
public void givenGenericFile_whenCastToTextFileAndInvokeGetWordCount_shouldFail() {
GenericFile genericFile = new GenericFile();
TextFile textFile = (TextFile) genericFile;
System.out.println(textFile.getWordCount());
}
}

View File

@@ -0,0 +1,14 @@
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);
}
}

View File

@@ -0,0 +1,15 @@
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);
}
}

View File

@@ -0,0 +1,17 @@
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"));
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.typeerasure;
import org.junit.Test;
public class TypeErasureUnitTest {
@Test(expected = ClassCastException.class)
public void givenIntegerStack_whenStringPushedAndAssignPoppedValueToInteger_shouldFail() {
IntegerStack integerStack = new IntegerStack(5);
Stack stack = integerStack;
stack.push("Hello");
Integer data = integerStack.pop();
}
@Test
public void givenAnyArray_whenInvokedPrintArray_shouldSucceed() {
Integer[] scores = new Integer[] { 100, 200, 10, 99, 20 };
ArrayContentPrintUtil.printArray(scores);
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear