[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
@@ -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,156 @@
|
||||
package com.baeldung.className;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class RetrievingClassNameUnitTest {
|
||||
|
||||
// Retrieving Simple Name
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetSimpleName_thenRetrievingClassName() {
|
||||
assertEquals("RetrievingClassName", RetrievingClassName.class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetSimpleName_thenInt() {
|
||||
assertEquals("int", int.class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetSimpleName_thenRetrievingClassNameWithBrackets() {
|
||||
assertEquals("RetrievingClassName[]", RetrievingClassName[].class.getSimpleName());
|
||||
assertEquals("RetrievingClassName[][]", RetrievingClassName[][].class.getSimpleName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetSimpleName_thenEmptyString() {
|
||||
assertEquals("", new RetrievingClassName() {}.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
// Retrieving Other Names
|
||||
// - Primitive Types
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetName_thenInt() {
|
||||
assertEquals("int", int.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetTypeName_thenInt() {
|
||||
assertEquals("int", int.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveInt_whenGetCanonicalName_thenInt() {
|
||||
assertEquals("int", int.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Object Types
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetTypeName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassName_whenGetCanonicalName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Inner Classes
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetName_thenCanonicalNameWithDollarSeparator() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetTypeName_thenCanonicalNameWithDollarSeparator() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClass_whenGetCanonicalName_thenCanonicalName() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass", RetrievingClassName.InnerClass.class.getCanonicalName());
|
||||
}
|
||||
|
||||
// - Anonymous Classes
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
|
||||
// These are the second and third appearences of an anonymous class in RetrievingClassNameUnitTest, hence $2 and $3 expectations
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$2", new RetrievingClassName() {}.getClass().getName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$3", new RetrievingClassName() {}.getClass().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetTypeName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
|
||||
// These are the fourth and fifth appearences of an anonymous class in RetrievingClassNameUnitTest, hence $4 and $5 expectations
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$4", new RetrievingClassName() {}.getClass().getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$5", new RetrievingClassName() {}.getClass().getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnonymousClass_whenGetCanonicalName_thenNull() {
|
||||
assertNull(new RetrievingClassName() {}.getClass().getCanonicalName());
|
||||
}
|
||||
|
||||
// - Arrays
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetName_thenOpeningBracketsAndPrimitiveIntLetter() {
|
||||
assertEquals("[I", int[].class.getName());
|
||||
assertEquals("[[I", int[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameGetName() {
|
||||
assertEquals("[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[].class.getName());
|
||||
assertEquals("[[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameInnerClassGetName() {
|
||||
assertEquals("[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[].class.getName());
|
||||
assertEquals("[[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[][].class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetTypeName_thenPrimitiveIntGetTypeNameWithBrackets() {
|
||||
assertEquals("int[]", int[].class.getTypeName());
|
||||
assertEquals("int[][]", int[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetTypeName_thenRetrievingClassNameGetTypeNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetTypeName_thenRetrievingClassNameInnerClassGetTypeNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[]", RetrievingClassName.InnerClass[].class.getTypeName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[][]", RetrievingClassName.InnerClass[][].class.getTypeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveIntArray_whenGetCanonicalName_thenPrimitiveIntGetCanonicalNameWithBrackets() {
|
||||
assertEquals("int[]", int[].class.getCanonicalName());
|
||||
assertEquals("int[][]", int[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameArray_whenGetCanonicalName_thenRetrievingClassNameGetCanonicalNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getCanonicalName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRetrievingClassNameInnerClassArray_whenGetCanonicalName_thenRetrievingClassNameInnerClassGetCanonicalNameWithBrackets() {
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[]", RetrievingClassName.InnerClass[].class.getCanonicalName());
|
||||
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[][]", RetrievingClassName.InnerClass[][].class.getCanonicalName());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.classnotfoundexception;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ClassNotFoundExceptionUnitTest {
|
||||
|
||||
@Test(expected = ClassNotFoundException.class)
|
||||
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
|
||||
Class.forName("oracle.jdbc.driver.OracleDriver");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.baeldung.compoundoperators;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class CompoundOperatorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAssignmentOperatorIsUsed_thenValueIsAssigned() {
|
||||
int x = 5;
|
||||
|
||||
assertEquals(5, x);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompoundAssignmentUsed_thenSameAsSimpleAssignment() {
|
||||
int a = 3, b = 3, c = -2;
|
||||
a = a * c; // Simple assignment operator
|
||||
b *= c; // Compound assignment operator
|
||||
|
||||
assertEquals(a, b);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAssignmentOperatorIsUsed_thenValueIsReturned() {
|
||||
long x = 1;
|
||||
long y = (x+=2);
|
||||
|
||||
assertEquals(3, y);
|
||||
assertEquals(y, x);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompoundOperatorsAreUsed_thenOperationsArePerformedAndAssigned() {
|
||||
//Simple assignment
|
||||
int x = 5; //x is 5
|
||||
|
||||
//Incrementation
|
||||
x += 5; //x is 10
|
||||
assertEquals(10, x);
|
||||
|
||||
//Decrementation
|
||||
x -= 2; //x is 8
|
||||
assertEquals(8, x);
|
||||
|
||||
//Multiplication
|
||||
x *= 2; //x is 16
|
||||
assertEquals(16, x);
|
||||
|
||||
//Division
|
||||
x /= 4; //x is 4
|
||||
assertEquals(4, x);
|
||||
|
||||
//Modulus
|
||||
x %= 3; //x is 1
|
||||
assertEquals(1, x);
|
||||
|
||||
|
||||
//Binary AND
|
||||
x &= 4; //x is 0
|
||||
assertEquals(0, x);
|
||||
|
||||
//Binary exclusive OR
|
||||
x ^= 4; //x is 4
|
||||
assertEquals(4, x);
|
||||
|
||||
//Binary inclusive OR
|
||||
x |= 8; //x is 12
|
||||
assertEquals(12, x);
|
||||
|
||||
|
||||
//Binary Left Shift
|
||||
x <<= 2; //x is 48
|
||||
assertEquals(48, x);
|
||||
|
||||
//Binary Right Shift
|
||||
x >>= 2; //x is 12
|
||||
assertEquals(12, x);
|
||||
|
||||
//Shift right zero fill
|
||||
x >>>= 1; //x is 6
|
||||
assertEquals(6, x);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenArrayIsNull_thenThrowNullException() {
|
||||
int[] numbers = null;
|
||||
|
||||
//Trying Incrementation
|
||||
numbers[2] += 5;
|
||||
}
|
||||
|
||||
@Test(expected = ArrayIndexOutOfBoundsException.class)
|
||||
public void whenArrayIndexNotCorrect_thenThrowArrayIndexException() {
|
||||
int[] numbers = {0, 1};
|
||||
|
||||
//Trying Incrementation
|
||||
numbers[2] += 5;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIndexIsCorrect_thenPerformOperation() {
|
||||
int[] numbers = {0, 1};
|
||||
|
||||
//Incrementation
|
||||
numbers[1] += 5;
|
||||
assertEquals(6, numbers[1]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,57 @@
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.enums.values;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author chris
|
||||
*/
|
||||
public class Element1UnitTest {
|
||||
|
||||
public Element1UnitTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() {
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownClass() {
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAccessingToString_thenItShouldEqualName() {
|
||||
for (Element1 e1 : Element1.values()) {
|
||||
assertEquals(e1.name(), e1.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallingValueOf_thenReturnTheCorrectEnum() {
|
||||
for (Element1 e1 : Element1.values()) {
|
||||
assertSame(e1, Element1.valueOf(e1.name()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.baeldung.enums.values;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author chris
|
||||
*/
|
||||
public class Element2UnitTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Element2UnitTest.class);
|
||||
|
||||
public Element2UnitTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() {
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownClass() {
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLocatebyLabel_thenReturnCorrectValue() {
|
||||
for (Element2 e2 : Element2.values()) {
|
||||
assertSame(e2, Element2.valueOfLabel(e2.label));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of toString method, of class Element2.
|
||||
*/
|
||||
@Test
|
||||
public void whenCallingToString_thenReturnLabel() {
|
||||
for (Element2 e2 : Element2.values()) {
|
||||
assertEquals(e2.label, e2.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.baeldung.enums.values;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author chris
|
||||
*/
|
||||
public class Element3UnitTest {
|
||||
|
||||
public Element3UnitTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() {
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownClass() {
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLocatebyLabel_thenReturnCorrectValue() {
|
||||
for (Element3 e3 : Element3.values()) {
|
||||
assertSame(e3, Element3.valueOfLabel(e3.label));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of toString method, of class Element3.
|
||||
*/
|
||||
@Test
|
||||
public void whenCallingToString_thenReturnLabel() {
|
||||
for (Element3 e3 : Element3.values()) {
|
||||
assertEquals(e3.label, e3.toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
package com.baeldung.enums.values;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author chris
|
||||
*/
|
||||
public class Element4UnitTest {
|
||||
|
||||
public Element4UnitTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() {
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownClass() {
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLocatebyLabel_thenReturnCorrectValue() {
|
||||
for (Element4 e4 : Element4.values()) {
|
||||
assertSame(e4, Element4.valueOfLabel(e4.label));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLocatebyAtmNum_thenReturnCorrectValue() {
|
||||
for (Element4 e4 : Element4.values()) {
|
||||
assertSame(e4, Element4.valueOfAtomicNumber(e4.atomicNumber));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLocatebyAtmWt_thenReturnCorrectValue() {
|
||||
for (Element4 e4 : Element4.values()) {
|
||||
assertSame(e4, Element4.valueOfAtomicWeight(e4.atomicWeight));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test of toString method, of class Element4.
|
||||
*/
|
||||
@Test
|
||||
public void whenCallingToString_thenReturnLabel() {
|
||||
for (Element4 e4 : Element4.values()) {
|
||||
assertEquals(e4.label, e4.toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,23 @@
|
||||
package com.baeldung.finalize;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FinalizeUnitTest {
|
||||
@Test
|
||||
public void whenGC_thenFinalizerExecuted() throws IOException {
|
||||
String firstLine = new Finalizable().readFirstLine();
|
||||
Assert.assertEquals("baeldung.com", firstLine);
|
||||
System.gc();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTryWResourcesExits_thenResourceClosed() throws IOException {
|
||||
try (CloseableResource resource = new CloseableResource()) {
|
||||
String firstLine = resource.readFirstLine();
|
||||
Assert.assertEquals("baeldung.com", firstLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.interfaces;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
|
||||
@RunWith(JUnit4.class)
|
||||
public class InnerInterfaceUnitTest {
|
||||
@Test
|
||||
public void whenCustomerListJoined_thenReturnsJoinedNames() {
|
||||
Customer.List customerList = new CommaSeparatedCustomers();
|
||||
customerList.Add(new Customer("customer1"));
|
||||
customerList.Add(new Customer("customer2"));
|
||||
assertEquals("customer1,customer2", customerList.getCustomerNames());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.java.enumiteration;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public enum DaysOfWeekEnum {
|
||||
SUNDAY("off"),
|
||||
MONDAY("working"),
|
||||
TUESDAY("working"),
|
||||
WEDNESDAY("working"),
|
||||
THURSDAY("working"),
|
||||
FRIDAY("working"),
|
||||
SATURDAY("off");
|
||||
|
||||
private String typeOfDay;
|
||||
|
||||
DaysOfWeekEnum(String typeOfDay) {
|
||||
this.typeOfDay = typeOfDay;
|
||||
}
|
||||
|
||||
public String getTypeOfDay() {
|
||||
return typeOfDay;
|
||||
}
|
||||
|
||||
public void setTypeOfDay(String typeOfDay) {
|
||||
this.typeOfDay = typeOfDay;
|
||||
}
|
||||
|
||||
public static Stream<DaysOfWeekEnum> stream() {
|
||||
return Stream.of(DaysOfWeekEnum.values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.java.enumiteration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class EnumIterationExamples {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Enum iteration using EnumSet:");
|
||||
EnumSet.allOf(DaysOfWeekEnum.class).forEach(day -> System.out.println(day));
|
||||
|
||||
System.out.println("Enum iteration using Stream:");
|
||||
DaysOfWeekEnum.stream().filter(d -> d.getTypeOfDay().equals("off")).forEach(System.out::println);
|
||||
|
||||
System.out.println("Enum iteration using a for loop:");
|
||||
for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) {
|
||||
System.out.println(day);
|
||||
}
|
||||
|
||||
System.out.println("Enum iteration using Arrays.asList():");
|
||||
Arrays.asList(DaysOfWeekEnum.values()).forEach(day -> System.out.println(day));
|
||||
|
||||
System.out.println("Add Enum values to ArrayList:");
|
||||
List<DaysOfWeekEnum> days = new ArrayList<>();
|
||||
days.add(DaysOfWeekEnum.FRIDAY);
|
||||
days.add(DaysOfWeekEnum.SATURDAY);
|
||||
days.add(DaysOfWeekEnum.SUNDAY);
|
||||
for (DaysOfWeekEnum day : days) {
|
||||
System.out.println(day);
|
||||
}
|
||||
System.out.println("Remove SATURDAY from the list:");
|
||||
days.remove(DaysOfWeekEnum.SATURDAY);
|
||||
if (!days.contains(DaysOfWeekEnum.SATURDAY)) {
|
||||
System.out.println("Saturday is no longer in the list");
|
||||
}
|
||||
for (DaysOfWeekEnum day : days) {
|
||||
System.out.println(day);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.nativekeyword;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public class DateTimeUtilsManualTest {
|
||||
|
||||
private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(DateTimeUtilsManualTest.class);
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() {
|
||||
System.loadLibrary("msvcr100");
|
||||
System.loadLibrary("libgcc_s_sjlj-1");
|
||||
System.loadLibrary("libstdc++-6");
|
||||
System.loadLibrary("nativedatetimeutils");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNativeLibsLoaded_thenNativeMethodIsAccessible() {
|
||||
DateTimeUtils dateTimeUtils = new DateTimeUtils();
|
||||
LOG.info("System time is : " + dateTimeUtils.getSystemTime());
|
||||
assertNotNull(dateTimeUtils.getSystemTime());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.noclassdeffounderror;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class NoClassDefFoundErrorUnitTest {
|
||||
|
||||
@Test(expected = NoClassDefFoundError.class)
|
||||
public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() {
|
||||
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
|
||||
sample.getClassWithInitErrors();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.objects;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CarUnitTest {
|
||||
|
||||
private Car car;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
car = new Car("Ford", "Focus", "red");
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void when_speedIncreased_then_verifySpeed() {
|
||||
car.increaseSpeed(30);
|
||||
assertEquals(30, car.getSpeed());
|
||||
|
||||
car.increaseSpeed(20);
|
||||
assertEquals(50, car.getSpeed());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void when_speedDecreased_then_verifySpeed() {
|
||||
car.increaseSpeed(50);
|
||||
assertEquals(50, car.getSpeed());
|
||||
|
||||
car.decreaseSpeed(30);
|
||||
assertEquals(20, car.getSpeed());
|
||||
|
||||
car.decreaseSpeed(20);
|
||||
assertEquals(0, car.getSpeed());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.packages;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.packages.domain.TodoItem;
|
||||
|
||||
public class PackagesUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenTodoItemAdded_ThenSizeIncreases() {
|
||||
TodoItem todoItem = new TodoItem();
|
||||
todoItem.setId(1L);
|
||||
todoItem.setDescription("Test the Todo List");
|
||||
todoItem.setDueDate(LocalDate.now());
|
||||
TodoList todoList = new TodoList();
|
||||
todoList.addTodoItem(todoItem);
|
||||
assertEquals(1, todoList.getTodoItems().size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.recursion;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RecursionExampleUnitTest {
|
||||
|
||||
RecursionExample recursion = new RecursionExample();
|
||||
|
||||
@Test
|
||||
public void testPowerOf10() {
|
||||
int p0 = recursion.powerOf10(0);
|
||||
int p1 = recursion.powerOf10(1);
|
||||
int p4 = recursion.powerOf10(4);
|
||||
|
||||
Assert.assertEquals(1, p0);
|
||||
Assert.assertEquals(10, p1);
|
||||
Assert.assertEquals(10000, p4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFibonacci() {
|
||||
int n0 = recursion.fibonacci(0);
|
||||
int n1 = recursion.fibonacci(1);
|
||||
int n7 = recursion.fibonacci(7);
|
||||
|
||||
Assert.assertEquals(0, n0);
|
||||
Assert.assertEquals(1, n1);
|
||||
Assert.assertEquals(13, n7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToBinary() {
|
||||
String b0 = recursion.toBinary(0);
|
||||
String b1 = recursion.toBinary(1);
|
||||
String b10 = recursion.toBinary(10);
|
||||
|
||||
Assert.assertEquals("0", b0);
|
||||
Assert.assertEquals("1", b1);
|
||||
Assert.assertEquals("1010", b10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCalculateTreeHeight() {
|
||||
BinaryNode root = new BinaryNode(1);
|
||||
root.setLeft(new BinaryNode(1));
|
||||
root.setRight(new BinaryNode(1));
|
||||
|
||||
root.getLeft().setLeft(new BinaryNode(1));
|
||||
root.getLeft().getLeft().setRight(new BinaryNode(1));
|
||||
root.getLeft().getLeft().getRight().setLeft(new BinaryNode(1));
|
||||
|
||||
root.getRight().setLeft(new BinaryNode(1));
|
||||
root.getRight().getLeft().setRight(new BinaryNode(1));
|
||||
|
||||
int height = recursion.calculateTreeHeight(root);
|
||||
|
||||
Assert.assertEquals(4, height);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.sneakythrows;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SneakyRunnableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallSneakyRunnableMethod_thenThrowException() {
|
||||
try {
|
||||
new SneakyRunnable().run();
|
||||
} catch (Exception e) {
|
||||
assertEquals(InterruptedException.class, e.getStackTrace());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.sneakythrows;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SneakyThrowsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallSneakyMethod_thenThrowSneakyException() {
|
||||
try {
|
||||
SneakyThrows.throwsSneakyIOException();
|
||||
} catch (Exception ex) {
|
||||
assertEquals("sneaky", ex.getMessage().toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,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,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