[JAVA-18123] Upgraded algorithms-modules to java 11 + Upgraded unit t… (#13437)

* [JAVA-18123] Upgraded algorithms-modules to java 11 + Upgraded unit tests to junit5

* [JAVA-18123] Clean up properties

---------

Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com>
This commit is contained in:
panos-kakos 2023-02-07 14:42:21 +00:00 committed by GitHub
parent 0dbc07b1de
commit 82757b243a
82 changed files with 740 additions and 721 deletions

View File

@ -1,22 +1,24 @@
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
public class AntColonyOptimizationLongRunningUnitTest {
class AntColonyOptimizationLongRunningUnitTest {
@Test
public void testGenerateRandomMatrix() {
void testGenerateRandomMatrix() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.generateRandomMatrix(5));
assertNotNull(antTSP.generateRandomMatrix(5));
}
@Test
public void testStartAntOptimization() {
void testStartAntOptimization() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
Assert.assertNotNull(antTSP.solve());
assertNotNull(antTSP.solve());
}
}

View File

@ -1,16 +1,19 @@
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
public class BinaryGeneticAlgorithmLongRunningUnitTest {
class BinaryGeneticAlgorithmLongRunningUnitTest {
@Test
public void testGA() {
void testGA() {
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
}
}

View File

@ -1,15 +1,17 @@
package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
public class SimulatedAnnealingLongRunningUnitTest {
class SimulatedAnnealingLongRunningUnitTest {
@Test
public void testSimulateAnnealing() {
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
void testSimulateAnnealing() {
assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
}
}

View File

@ -1,23 +1,25 @@
package com.baeldung.algorithms;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.hillclimbing.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class HillClimbingAlgorithmUnitTest {
class HillClimbingAlgorithmUnitTest {
private Stack<String> initStack;
private Stack<String> goalStack;
@Before
@BeforeEach
public void initStacks() {
String blockArr[] = { "B", "C", "D", "A" };
String goalBlockArr[] = { "A", "B", "C", "D" };
@ -30,7 +32,7 @@ public class HillClimbingAlgorithmUnitTest {
}
@Test
public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
HillClimbing hillClimbing = new HillClimbing();
List<State> path;
@ -46,7 +48,7 @@ public class HillClimbingAlgorithmUnitTest {
}
@Test
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
HillClimbing hillClimbing = new HillClimbing();
List<Stack<String>> initList = new ArrayList<>();
initList.add(initStack);

View File

@ -1,14 +1,16 @@
package com.baeldung.algorithms;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.automata.*;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public final class RtFiniteStateMachineLongRunningUnitTest {
class RtFiniteStateMachineLongRunningUnitTest {
@Test
public void acceptsSimplePair() {
void acceptsSimplePair() {
String json = "{\"key\":\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
@ -18,7 +20,7 @@ public final class RtFiniteStateMachineLongRunningUnitTest {
}
@Test
public void acceptsMorePairs() {
void acceptsMorePairs() {
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
@ -27,13 +29,15 @@ public final class RtFiniteStateMachineLongRunningUnitTest {
assertTrue(machine.canStop());
}
@Test(expected = IllegalArgumentException.class)
public void missingColon() {
@Test
void missingColon() {
String json = "{\"key\"\"value\"}";
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
machine = machine.switchState(String.valueOf(json.charAt(i)));
}
assertThrows(IllegalArgumentException.class, () -> {
FiniteStateMachine machine = this.buildJsonStateMachine();
for (int i = 0; i < json.length(); i++) {
machine = machine.switchState(String.valueOf(json.charAt(i)));
}
});
}
/**

View File

@ -1,54 +1,54 @@
package com.baeldung.algorithms.kthlargest;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class FindKthLargestUnitTest {
class FindKthLargestUnitTest {
private FindKthLargest findKthLargest;
private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 };
@Before
@BeforeEach
public void setup() {
findKthLargest = new FindKthLargest();
}
@Test
public void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8);
}
@Test
public void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8);
}
@Test
public void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
@Test
public void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
@Test
public void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3);
}
@Test
public void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);

View File

@ -1,23 +1,24 @@
package com.baeldung.algorithms.minimax;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.*;
import com.baeldung.algorithms.minimax.MiniMax;
import com.baeldung.algorithms.minimax.Tree;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class MinimaxUnitTest {
class MinimaxUnitTest {
private Tree gameTree;
private MiniMax miniMax;
@Before
@BeforeEach
public void initMiniMaxUtility() {
miniMax = new MiniMax();
}
@Test
public void givenMiniMax_whenConstructTree_thenNotNullTree() {
void givenMiniMax_whenConstructTree_thenNotNullTree() {
assertNull(gameTree);
miniMax.constructTree(6);
gameTree = miniMax.getTree();
@ -25,7 +26,7 @@ public class MinimaxUnitTest {
}
@Test
public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
void givenMiniMax_whenCheckWin_thenComputeOptimal() {
miniMax.constructTree(6);
boolean result = miniMax.checkWin();
assertTrue(result);

View File

@ -1,6 +1,6 @@
package com.baeldung.algorithms;
import org.junit.Test;
import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
import com.baeldung.algorithms.ga.dijkstra.Graph;
@ -11,7 +11,9 @@ import java.util.List;
import static org.junit.Assert.assertTrue;
public class DijkstraAlgorithmLongRunningUnitTest {
import org.junit.jupiter.api.Test;
class DijkstraAlgorithmLongRunningUnitTest {
@Test
public void whenSPPSolved_thenCorrect() {

View File

@ -1,5 +1,6 @@
package com.baeldung.algorithms.astar.underground;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
@ -10,22 +11,22 @@ import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.astar.Graph;
import com.baeldung.algorithms.astar.RouteFinder;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
@Slf4j
public class RouteFinderIntegrationTest {
class RouteFinderIntegrationTest {
private Graph<Station> underground;
private RouteFinder<Station> routeFinder;
@Before
@BeforeEach
public void setUp() throws Exception {
Set<Station> stations = new HashSet<>();
Map<String, Set<String>> connections = new HashMap<>();
@ -641,7 +642,7 @@ public class RouteFinderIntegrationTest {
}
@Test
public void findRoute() {
void findRoute() {
List<Station> route = routeFinder.findRoute(underground.getNode("74"), underground.getNode("7"));
assertThat(route).size().isPositive();

View File

@ -1,21 +0,0 @@
package com.baeldung.algorithms.editdistance;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
public class EditDistanceDataProvider {
@Parameters
public static Collection<Object[]> getLists() {
return Arrays.asList(new Object[][] {
{ "", "", 0 },
{ "ago", "", 3 },
{ "", "do", 2 },
{ "abc", "adc", 1 },
{ "peek", "pesek", 1 },
{ "sunday", "saturday", 3 }
});
}
}

View File

@ -1,32 +1,39 @@
package com.baeldung.algorithms.editdistance;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(Parameterized.class)
public class EditDistanceUnitTest extends EditDistanceDataProvider {
import java.util.stream.Stream;
private String x;
private String y;
private int result;
public EditDistanceUnitTest(String a, String b, int res) {
super();
x = a;
y = b;
result = res;
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
@Test
public void testEditDistance_RecursiveImplementation() {
import org.junit.jupiter.params.provider.MethodSource;
class EditDistanceUnitTest {
@ParameterizedTest
@MethodSource("provideArguments")
void testEditDistance_RecursiveImplementation(String x, String y, int result) {
assertEquals(result, EditDistanceRecursive.calculate(x, y));
}
@Test
public void testEditDistance_givenDynamicProgrammingImplementation() {
@ParameterizedTest
@MethodSource("provideArguments")
void testEditDistance_givenDynamicProgrammingImplementation(String x, String y, int result) {
assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y));
}
static Stream<? extends Arguments> provideArguments() {
return Stream.of(new Object[][] {
{ "", "", 0 },
{ "ago", "", 3 },
{ "", "do", 2 },
{ "abc", "adc", 1 },
{ "peek", "pesek", 1 },
{ "sunday", "saturday", 3 }
}).map(Arguments::of);
}
}

View File

@ -1,23 +1,16 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(value = Parameterized.class)
public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public CycleDetectionBruteForceUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase {
@Test
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists);
@ParameterizedTest
@MethodSource("getLists")
void givenList_detectLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists);
}
}

View File

@ -1,23 +1,16 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
import static org.junit.jupiter.api.Assertions.assertEquals;
public CycleDetectionByFastAndSlowIteratorsUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@Test
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase {
@ParameterizedTest
@MethodSource("getLists")
void givenList_detectLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -1,23 +1,17 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
import static org.junit.jupiter.api.Assertions.assertEquals;
public CycleDetectionByHashingUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@Test
public void givenList_detectLoop() {
Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists);
class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase {
@ParameterizedTest
@MethodSource("getLists")
void givenList_detectLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists);
}
}

View File

@ -7,7 +7,7 @@ import org.junit.runners.Parameterized.Parameters;
public class CycleDetectionTestBase {
@Parameters
public static Collection<Object[]> getLists() {
return Arrays.asList(new Object[][] {
{ createList(), false },

View File

@ -1,24 +1,19 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public CycleRemovalBruteForceUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@Test
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase {
@ParameterizedTest
@MethodSource("getLists")
void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head));
assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -1,24 +1,17 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@RunWith(value = Parameterized.class)
public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public CycleRemovalByCountingLoopNodesUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase {
@Test
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
@ParameterizedTest
@MethodSource("getLists")
void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head));
assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -1,24 +1,19 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(value = Parameterized.class)
public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase {
boolean cycleExists;
Node<Integer> head;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public CycleRemovalWithoutCountingLoopNodesUnitTest(Node<Integer> head, boolean cycleExists) {
super();
this.cycleExists = cycleExists;
this.head = head;
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@Test
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head));
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase {
@ParameterizedTest
@MethodSource("getLists")
void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node<Integer> head, boolean cycleExists) {
assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head));
assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
}
}

View File

@ -1,84 +1,84 @@
package com.baeldung.algorithms.moneywords;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.numberwordconverter.NumberWordConverter;
public class NumberWordConverterUnitTest {
class NumberWordConverterUnitTest {
@Test
public void whenMoneyNegative_thenReturnInvalidInput() {
void whenMoneyNegative_thenReturnInvalidInput() {
assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13));
}
@Test
public void whenZeroDollarsGiven_thenReturnEmptyString() {
void whenZeroDollarsGiven_thenReturnEmptyString() {
assertEquals("", NumberWordConverter.getMoneyIntoWords(0));
}
@Test
public void whenOnlyDollarsGiven_thenReturnWords() {
void whenOnlyDollarsGiven_thenReturnWords() {
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
}
@Test
public void whenOnlyCentsGiven_thenReturnWords() {
void whenOnlyCentsGiven_thenReturnWords() {
assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6));
}
@Test
public void whenAlmostAMillioDollarsGiven_thenReturnWords() {
void whenAlmostAMillioDollarsGiven_thenReturnWords() {
String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999));
}
@Test
public void whenThirtyMillionDollarsGiven_thenReturnWords() {
void whenThirtyMillionDollarsGiven_thenReturnWords() {
String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978));
}
@Test
public void whenTwoBillionDollarsGiven_thenReturnWords() {
void whenTwoBillionDollarsGiven_thenReturnWords() {
String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810));
}
@Test
public void whenGivenDollarsAndCents_thenReturnWords() {
void whenGivenDollarsAndCents_thenReturnWords() {
String expectedResult = "nine hundred twenty four dollars and sixty cents";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6));
}
@Test
public void whenOneDollarAndNoCents_thenReturnDollarSingular() {
void whenOneDollarAndNoCents_thenReturnDollarSingular() {
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
}
@Test
public void whenNoDollarsAndOneCent_thenReturnCentSingular() {
void whenNoDollarsAndOneCent_thenReturnCentSingular() {
assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01));
}
@Test
public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02));
}
@Test
public void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99));
}
@Test
public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959));
}
@Test
public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310"));
}
}

View File

@ -1,6 +1,8 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
@ -9,15 +11,15 @@ import org.jgrapht.alg.HamiltonianCycle;
import org.jgrapht.generate.CompleteGraphGenerator;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CompleteGraphUnitTest {
class CompleteGraphUnitTest {
static SimpleWeightedGraph<String, DefaultEdge> completeGraph;
static int size = 10;
@Before
@BeforeEach
public void createCompleteGraph() {
completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
CompleteGraphGenerator<String, DefaultEdge> completeGenerator = new CompleteGraphGenerator<String, DefaultEdge>(size);

View File

@ -1,7 +1,9 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
@ -21,13 +23,13 @@ import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DirectedSubgraph;
import org.jgrapht.traverse.BreadthFirstIterator;
import org.jgrapht.traverse.DepthFirstIterator;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DirectedGraphUnitTest {
class DirectedGraphUnitTest {
DirectedGraph<String, DefaultEdge> directedGraph;
@Before
@BeforeEach
public void createDirectedGraph() {
directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
IntStream.range(1, 10).forEach(i -> {
@ -46,7 +48,7 @@ public class DirectedGraphUnitTest {
}
@Test
public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() {
void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() {
StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph);
List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs();
List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet());
@ -60,7 +62,7 @@ public class DirectedGraphUnitTest {
}
@Test
public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() {
void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() {
CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(directedGraph);
assertTrue(cycleDetector.detectCycles());
Set<String> cycleVertices = cycleDetector.findCycles();
@ -68,26 +70,26 @@ public class DirectedGraphUnitTest {
}
@Test
public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() {
void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() {
DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph);
assertNotNull(depthFirstIterator);
}
@Test
public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() {
void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() {
BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph);
assertNotNull(breadthFirstIterator);
}
@Test
public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() {
void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() {
DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph);
List<String> shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList();
assertNotNull(shortestPath);
}
@Test
public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() {
void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() {
BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph);
List<String> shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList();
assertNotNull(shortestPath);

View File

@ -1,7 +1,7 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.stream.IntStream;
@ -9,13 +9,13 @@ import org.jgrapht.GraphPath;
import org.jgrapht.alg.cycle.HierholzerEulerianCycle;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class EulerianCircuitUnitTest {
class EulerianCircuitUnitTest {
SimpleWeightedGraph<String, DefaultEdge> simpleGraph;
@Before
@BeforeEach
public void createGraphWithEulerianCircuit() {
simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
IntStream.range(1, 6).forEach(i -> {

View File

@ -1,6 +1,8 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Color;
import java.awt.image.BufferedImage;
@ -12,18 +14,18 @@ import javax.imageio.ImageIO;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer;
public class GraphImageGenerationUnitTest {
class GraphImageGenerationUnitTest {
static DefaultDirectedGraph<String, DefaultEdge> g;
@Before
@BeforeEach
public void createGraph() throws IOException {
File imgFile = new File("src/test/resources/graph1.png");
imgFile.createNewFile();
@ -39,14 +41,14 @@ public class GraphImageGenerationUnitTest {
g.addEdge(x3, x1);
}
@After
@AfterEach
public void cleanup() {
File imgFile = new File("src/test/resources/graph1.png");
imgFile.deleteOnExit();
}
@Test
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());

View File

@ -1,14 +1,14 @@
package com.baeldung.algorithms.analysis;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class AnalysisRunnerLiveTest {
class AnalysisRunnerLiveTest {
int n = 10;
int total = 0;
@Test
public void whenConstantComplexity_thenConstantRuntime() {
void whenConstantComplexity_thenConstantRuntime() {
System.out.println("**** n = " + n + " ****");
System.out.println();
@ -22,7 +22,7 @@ public class AnalysisRunnerLiveTest {
}
@Test
public void whenLogarithmicComplexity_thenLogarithmicRuntime() {
void whenLogarithmicComplexity_thenLogarithmicRuntime() {
// Logarithmic Time
System.out.println("**** Logarithmic Time ****");
for (int i = 1; i < n; i = i * 2) {
@ -34,7 +34,7 @@ public class AnalysisRunnerLiveTest {
}
@Test
public void whenLinearComplexity_thenLinearRuntime() {
void whenLinearComplexity_thenLinearRuntime() {
// Linear Time
System.out.println("**** Linear Time ****");
for (int i = 0; i < n; i++) {
@ -47,7 +47,7 @@ public class AnalysisRunnerLiveTest {
}
@Test
public void whenNLogNComplexity_thenNLogNRuntime() {
void whenNLogNComplexity_thenNLogNRuntime() {
// N Log N Time
System.out.println("**** nlogn Time ****");
total = 0;
@ -64,7 +64,7 @@ public class AnalysisRunnerLiveTest {
}
@Test
public void whenQuadraticComplexity_thenQuadraticRuntime() {
void whenQuadraticComplexity_thenQuadraticRuntime() {
// Quadratic Time
System.out.println("**** Quadratic Time ****");
total = 0;
@ -81,7 +81,7 @@ public class AnalysisRunnerLiveTest {
}
@Test
public void whenCubicComplexity_thenCubicRuntime() {
void whenCubicComplexity_thenCubicRuntime() {
// Cubic Time
System.out.println("**** Cubic Time ****");
total = 0;
@ -100,7 +100,7 @@ public class AnalysisRunnerLiveTest {
}
@Test
public void whenExponentialComplexity_thenExponentialRuntime() {
void whenExponentialComplexity_thenExponentialRuntime() {
// Exponential Time
System.out.println("**** Exponential Time ****");
total = 0;
@ -115,7 +115,7 @@ public class AnalysisRunnerLiveTest {
}
@Test
public void whenFactorialComplexity_thenFactorialRuntime() {
void whenFactorialComplexity_thenFactorialRuntime() {
// Factorial Time
System.out.println("**** Factorial Time ****");
total = 0;

View File

@ -11,10 +11,10 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class SortedListCheckerUnitTest {
class SortedListCheckerUnitTest {
private List<String> sortedListOfString;
private List<String> unsortedListOfString;
@ -23,7 +23,7 @@ public class SortedListCheckerUnitTest {
private List<Employee> employeesSortedByName;
private List<Employee> employeesNotSortedByName;
@Before
@BeforeEach
public void setUp() {
sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY");
unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada");
@ -34,72 +34,72 @@ public class SortedListCheckerUnitTest {
}
@Test
public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue();
}
@Test
public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue();
}
@Test
public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse();
}
@Test
public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
}
@Test
public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
}
@Test
public void givenSortedList_whenUsingRecursion_thenReturnTrue() {
void givenSortedList_whenUsingRecursion_thenReturnTrue() {
assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue();
}
@Test
public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue();
}
@Test
public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse();
}
@Test
public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue();
}
@Test
public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse();
}
@Test
public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
}
@Test
public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
}
@Test
public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue();
}
@Test
public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse();
}

View File

@ -1,37 +1,37 @@
package com.baeldung.algorithms.enumstatemachine;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class LeaveRequestStateUnitTest {
class LeaveRequestStateUnitTest {
@Test
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
LeaveRequestState state = LeaveRequestState.Escalated;
assertEquals(state.responsiblePerson(), "Team Leader");
assertEquals( "Team Leader", state.responsiblePerson());
}
@Test
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
LeaveRequestState state = LeaveRequestState.Approved;
assertEquals(state.responsiblePerson(), "Department Manager");
assertEquals( "Department Manager" , state.responsiblePerson());
}
@Test
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
LeaveRequestState state = LeaveRequestState.Submitted;
state = state.nextState();
assertEquals(state, LeaveRequestState.Escalated);
assertEquals(LeaveRequestState.Escalated, state);
state = state.nextState();
assertEquals(state, LeaveRequestState.Approved);
assertEquals(LeaveRequestState.Approved, state);
state = state.nextState();
assertEquals(state, LeaveRequestState.Approved);
assertEquals(LeaveRequestState.Approved, state);
}
}

View File

@ -1,14 +1,14 @@
package com.baeldung.algorithms.graphcycledetection;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.graphcycledetection.domain.Graph;
import com.baeldung.algorithms.graphcycledetection.domain.Vertex;
public class GraphCycleDetectionUnitTest {
class GraphCycleDetectionUnitTest {
@Test
public void givenGraph_whenCycleExists_thenReturnTrue() {
@ -33,7 +33,7 @@ public class GraphCycleDetectionUnitTest {
}
@Test
public void givenGraph_whenNoCycleExists_thenReturnFalse() {
void givenGraph_whenNoCycleExists_thenReturnFalse() {
Vertex vertexA = new Vertex("A");
Vertex vertexB = new Vertex("B");

View File

@ -1,14 +1,11 @@
package com.baeldung.algorithms.printtriangles;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@RunWith(JUnitParamsRunner.class)
public class PrintTriangleExamplesUnitTest {
class PrintTriangleExamplesUnitTest {
private static Object[][] rightTriangles() {
String expected0 = "";
@ -38,9 +35,9 @@ public class PrintTriangleExamplesUnitTest {
};
}
@Test
@Parameters(method = "rightTriangles")
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
@ParameterizedTest
@MethodSource("rightTriangles")
void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
assertEquals(expected, actual);
@ -74,24 +71,24 @@ public class PrintTriangleExamplesUnitTest {
};
}
@Test
@Parameters(method = "isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
@ParameterizedTest
@MethodSource("isoscelesTriangles")
void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangle(nrOfRows);
assertEquals(expected, actual);
}
@Test
@Parameters(method = "isoscelesTriangles")
@ParameterizedTest
@MethodSource("isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
assertEquals(expected, actual);
}
@Test
@Parameters(method = "isoscelesTriangles")
@ParameterizedTest
@MethodSource("isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleUsingSubstringIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingSubstring(nrOfRows);

View File

@ -1,13 +1,14 @@
package com.baeldung.algorithms.romannumerals;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class RomanArabicConverterUnitTest {
class RomanArabicConverterUnitTest {
@Test
public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() {
void given2018Roman_WhenConvertingToArabic_ThenReturn2018() {
String roman2018 = "MMXVIII";
@ -17,7 +18,7 @@ public class RomanArabicConverterUnitTest {
}
@Test
public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() {
void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() {
int arabic1999 = 1999;

View File

@ -2,14 +2,14 @@ package com.baeldung.algorithms.twopointertechnique;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class LinkedListFindMiddleUnitTest {
class LinkedListFindMiddleUnitTest {
LinkedListFindMiddle linkedListFindMiddle = new LinkedListFindMiddle();
@Test
public void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() {
void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() {
MyNode<String> head = createNodesList(8);

View File

@ -1,10 +1,10 @@
package com.baeldung.algorithms.twopointertechnique;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class RotateArrayUnitTest {
class RotateArrayUnitTest {
private RotateArray rotateArray = new RotateArray();
@ -13,7 +13,7 @@ public class RotateArrayUnitTest {
private int step;
@Test
public void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() {
void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() {
inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
step = 4;

View File

@ -1,11 +1,12 @@
package com.baeldung.algorithms.twopointertechnique;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TwoSumUnitTest {
class TwoSumUnitTest {
private TwoSum twoSum = new TwoSum();
@ -14,7 +15,7 @@ public class TwoSumUnitTest {
private int targetValue;
@Test
public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() {
void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
@ -24,7 +25,7 @@ public class TwoSumUnitTest {
}
@Test
public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() {
void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
@ -34,7 +35,7 @@ public class TwoSumUnitTest {
}
@Test
public void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() {
void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
@ -44,7 +45,7 @@ public class TwoSumUnitTest {
}
@Test
public void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() {
void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() {
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };

View File

@ -1,18 +1,18 @@
package com.baeldung.counter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import com.baeldung.counter.CounterUtil.MutableInteger;
public class CounterUnitTest {
class CounterUnitTest {
@Test
public void whenMapWithWrapperAsCounter_runsSuccessfully() {
void whenMapWithWrapperAsCounter_runsSuccessfully() {
Map<String, Integer> counterMap = new HashMap<>();
CounterUtil.counterWithWrapperObject(counterMap);
@ -23,7 +23,7 @@ public class CounterUnitTest {
}
@Test
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
Map<String, Long> counterMap = new HashMap<>();
CounterUtil.counterWithLambdaAndWrapper(counterMap);
@ -34,7 +34,7 @@ public class CounterUnitTest {
}
@Test
public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
void whenMapWithMutableIntegerCounter_runsSuccessfully() {
Map<String, MutableInteger> counterMap = new HashMap<>();
CounterUtil.counterWithMutableInteger(counterMap);
assertEquals(3, counterMap.get("China")
@ -44,7 +44,7 @@ public class CounterUnitTest {
}
@Test
public void whenMapWithPrimitiveArray_runsSuccessfully() {
void whenMapWithPrimitiveArray_runsSuccessfully() {
Map<String, int[]> counterMap = new HashMap<>();
CounterUtil.counterWithPrimitiveArray(counterMap);
assertEquals(3, counterMap.get("China")[0]);

View File

@ -1,22 +1,22 @@
package com.baeldung.folding;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class FoldingHashUnitTest {
class FoldingHashUnitTest {
@Test
public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int value = hasher.hash("Java language", 2, 100_000);
assertEquals(value, 48933);
}
@Test
public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int java = hasher.hash("Java language", 2, 100_000);
final int vaja = hasher.hash("vaJa language", 2, 100_000);
@ -24,28 +24,28 @@ public class FoldingHashUnitTest {
}
@Test
public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 5 }, 0, 2);
assertArrayEquals(new int[] { 5 }, value);
}
@Test
public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3);
assertArrayEquals(new int[] { 1, 2, 3 }, value);
}
@Test
public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
assertArrayEquals(new int[] { 2, 3 }, value);
}
@Test
public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000);
assertArrayEquals(new int[] { 3, 4, 5 }, value);

View File

@ -1,18 +1,19 @@
package com.baeldung.algorithms;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
import com.baeldung.algorithms.middleelementlookup.Node;
import org.junit.Test;
import java.util.LinkedList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.jupiter.api.Test;
public class MiddleElementLookupUnitTest {
class MiddleElementLookupUnitTest {
@Test
public void whenFindingMiddleLinkedList_thenMiddleFound() {
void whenFindingMiddleLinkedList_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementLinkedList(createLinkedList(5))
.get());
@ -22,7 +23,7 @@ public class MiddleElementLookupUnitTest {
}
@Test
public void whenFindingMiddleFromHead_thenMiddleFound() {
void whenFindingMiddleFromHead_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead(createNodesList(5))
.get());
@ -32,7 +33,7 @@ public class MiddleElementLookupUnitTest {
}
@Test
public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() {
void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(createNodesList(5))
.get());
@ -42,7 +43,7 @@ public class MiddleElementLookupUnitTest {
}
@Test
public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() {
void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(createNodesList(5))
.get());
@ -52,7 +53,7 @@ public class MiddleElementLookupUnitTest {
}
@Test
public void whenListEmptyOrNull_thenMiddleNotFound() {
void whenListEmptyOrNull_thenMiddleNotFound() {
// null list
assertFalse(MiddleElementLookup
.findMiddleElementLinkedList(null)

View File

@ -34,6 +34,23 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>${xml-bind-api.version}</version>
</dependency>
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>${jaxb-runtime.version}</version>
</dependency>
</dependencies>
<properties>
<xml-bind-api.version>4.0.0</xml-bind-api.version>
<jaxb-runtime.version>4.0.0</jaxb-runtime.version>
</properties>
</project>

View File

@ -2,13 +2,15 @@ package com.baeldung.algorithms.conversion;
import java.math.BigInteger;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.io.BaseEncoding;
import jakarta.xml.bind.DatatypeConverter;
public class HexStringConverter {
/**
@ -90,7 +92,7 @@ public class HexStringConverter {
return DatatypeConverter.parseHexBinary(hexString);
}
public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException {
public String encodeUsingApacheCommons(byte[] bytes) {
return Hex.encodeHexString(bytes);
}

View File

@ -1,22 +1,23 @@
package com.baeldung.algorithms.balancedbinarytree;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider {
import org.junit.jupiter.api.Test;
class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider {
@Test
public void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() {
void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() {
for (Tree tree : balancedTrees()) {
assertTrue(toString(tree) + " should be balanced", BalancedBinaryTree.isBalanced(tree));
assertTrue(BalancedBinaryTree.isBalanced(tree), toString(tree) + " should be balanced");
}
}
@Test
public void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() {
void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() {
for (Tree tree : unbalancedTrees()) {
assertFalse(toString(tree) + " should not be balanced", BalancedBinaryTree.isBalanced(tree));
assertFalse(BalancedBinaryTree.isBalanced(tree), toString(tree) + " should not be balanced");
}
}

View File

@ -5,27 +5,31 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class BinaryGapUnitTest {
class BinaryGapUnitTest {
@Test public void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
@Test
void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(63);
assertEquals(0, result);
}
@Test public void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
@Test
void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(40);
assertEquals(1, result);
}
@Test public void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
@Test
void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(9);
assertEquals(2, result);
}
@Test public void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
@Test
void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(145);
assertEquals(3, result);

View File

@ -1,17 +1,18 @@
package com.baeldung.algorithms.combinatorics;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import org.junit.jupiter.api.Test;
public class CombinatoricsUnitTest {
class CombinatoricsUnitTest {
@Test
public void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() {
void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() {
List<Integer> sequence = Arrays.asList();
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
@ -20,7 +21,7 @@ public class CombinatoricsUnitTest {
}
@Test
public void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() {
void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() {
List<Integer> sequence = Arrays.asList(1);
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
@ -31,7 +32,7 @@ public class CombinatoricsUnitTest {
}
@Test
public void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() {
void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() {
List<Integer> sequence = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
@ -41,7 +42,7 @@ public class CombinatoricsUnitTest {
}
@Test
public void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() {
void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() {
List<Integer> set = Arrays.asList(1, 2);
List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
@ -50,7 +51,7 @@ public class CombinatoricsUnitTest {
}
@Test
public void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() {
void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() {
List<Integer> set = Arrays.asList(1, 2, 3);
List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
@ -60,7 +61,7 @@ public class CombinatoricsUnitTest {
}
@Test
public void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() {
void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() {
List<Integer> set = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> combinations = Combinatorics.combinations(set, 2);
@ -70,7 +71,7 @@ public class CombinatoricsUnitTest {
}
@Test
public void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() {
void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() {
List<Character> sequence = Arrays.asList('a', 'b', 'c', 'd');
List<List<Character>> combinations = Combinatorics.powerSet(sequence);

View File

@ -1,27 +1,27 @@
package com.baeldung.algorithms.conversion;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.apache.commons.codec.DecoderException;
import org.hamcrest.text.IsEqualIgnoringCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.conversion.HexStringConverter;
public class ByteArrayConverterUnitTest {
class ByteArrayConverterUnitTest {
private HexStringConverter hexStringConverter;
@Before
@BeforeEach
public void setup() {
hexStringConverter = new HexStringConverter();
}
@Test
public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
if(hexString.charAt(0) == '0') {
@ -32,7 +32,7 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes);
@ -40,7 +40,7 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldDecodeHexStringToByteArrayUsingBigInteger() {
void shouldDecodeHexStringToByteArrayUsingBigInteger() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
@ -48,7 +48,7 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeHexString(bytes);
@ -56,20 +56,22 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeHexString(hexString);
assertArrayEquals(bytes, output);
}
@Test(expected=IllegalArgumentException.class)
public void shouldDecodeHexToByteWithInvalidHexCharacter() {
hexStringConverter.hexToByte("fg");
@Test
void shouldDecodeHexToByteWithInvalidHexCharacter() {
assertThrows(IllegalArgumentException.class, () -> {
hexStringConverter.hexToByte("fg");
});
}
@Test
public void shouldEncodeByteArrayToHexStringDataTypeConverter() {
void shouldEncodeByteArrayToHexStringDataTypeConverter() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingDataTypeConverter(bytes);
@ -77,7 +79,7 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString);
@ -85,7 +87,7 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldEncodeByteArrayToHexStringUsingGuava() {
void shouldEncodeByteArrayToHexStringUsingGuava() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingGuava(bytes);
@ -93,7 +95,7 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldDecodeHexStringToByteArrayUsingGuava() {
void shouldDecodeHexStringToByteArrayUsingGuava() {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingGuava(hexString);
@ -101,7 +103,7 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
String output = hexStringConverter.encodeUsingApacheCommons(bytes);
@ -109,7 +111,7 @@ public class ByteArrayConverterUnitTest {
}
@Test
public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
byte[] bytes = getSampleBytes();
String hexString = getSampleHexString();
byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString);

View File

@ -1,16 +1,18 @@
package com.baeldung.algorithms.integerstreammedian;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.Test;
public class MedianOfIntegerStreamUnitTest {
class MedianOfIntegerStreamUnitTest {
@Test
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() {
void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() {
MedianOfIntegerStream mis = new MedianOfIntegerStream();
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
mis.add(e.getKey());
@ -19,7 +21,7 @@ public class MedianOfIntegerStreamUnitTest {
}
@Test
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() {
void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() {
MedianOfIntegerStream2 mis = new MedianOfIntegerStream2();
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
mis.add(e.getKey());

View File

@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class KnapsackUnitTest {
class KnapsackUnitTest {
@Test
public void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() {
void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() {
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
final int n = 10;
@ -19,7 +19,7 @@ public class KnapsackUnitTest {
}
@Test
public void givenZeroItems_whenCalculateMax_thenOutputZero() {
void givenZeroItems_whenCalculateMax_thenOutputZero() {
final int[] w = new int[] {};
final int[] v = new int[] {};
final int n = 0;
@ -31,7 +31,7 @@ public class KnapsackUnitTest {
}
@Test
public void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() {
void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() {
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
final int n = 10;

View File

@ -5,10 +5,10 @@ import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.mergesortedarrays.SortedArrays;
public class SortedArraysUnitTest {
class SortedArraysUnitTest {
@Test
public void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() {
void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() {
int[] foo = { 3, 7 };
int[] bar = { 4, 8, 11 };
@ -18,7 +18,7 @@ public class SortedArraysUnitTest {
}
@Test
public void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() {
void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() {
int[] foo = { 3, 3, 7 };
int[] bar = { 4, 8, 8, 11 };

View File

@ -1,14 +1,15 @@
package com.baeldung.algorithms.prim;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class PrimUnitTest {
import org.junit.jupiter.api.Test;
class PrimUnitTest {
@Test
public void givenAGraph_whenPrimRuns_thenPrintMST() {
void givenAGraph_whenPrimRuns_thenPrintMST() {
Prim prim = new Prim(createGraph());
System.out.println(prim.originalGraphToString());
System.out.println("----------------");

View File

@ -1,49 +1,49 @@
package com.baeldung.algorithms.relativelyprime;
import org.junit.Test;
import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*;
import static org.assertj.core.api.Assertions.assertThat;
public class RelativelyPrimeUnitTest {
import org.junit.jupiter.api.Test;
class RelativelyPrimeUnitTest {
@Test
public void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() {
void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() {
boolean result = iterativeRelativelyPrime(45, 35);
assertThat(result).isFalse();
}
@Test
public void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() {
void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() {
boolean result = iterativeRelativelyPrime(500, 501);
assertThat(result).isTrue();
}
@Test
public void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() {
void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() {
boolean result = recursiveRelativelyPrime(45, 35);
assertThat(result).isFalse();
}
@Test
public void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() {
void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() {
boolean result = recursiveRelativelyPrime(500, 501);
assertThat(result).isTrue();
}
@Test
public void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() {
void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() {
boolean result = bigIntegerRelativelyPrime(45, 35);
assertThat(result).isFalse();
}
@Test
public void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() {
void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() {
boolean result = bigIntegerRelativelyPrime(500, 501);
assertThat(result).isTrue();

View File

@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class TreeReverserUnitTest {
class TreeReverserUnitTest {
@Test
public void givenTreeWhenReversingRecursivelyThenReversed() {
void givenTreeWhenReversingRecursivelyThenReversed() {
TreeReverser reverser = new TreeReverser();
TreeNode treeNode = createBinaryTree();
@ -19,7 +19,7 @@ public class TreeReverserUnitTest {
}
@Test
public void givenTreeWhenReversingIterativelyThenReversed() {
void givenTreeWhenReversingIterativelyThenReversed() {
TreeReverser reverser = new TreeReverser();
TreeNode treeNode = createBinaryTree();

View File

@ -1,80 +1,81 @@
package com.baeldung.algorithms.balancedbrackets;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BalancedBracketsUsingDequeUnitTest {
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class BalancedBracketsUsingDequeUnitTest {
private BalancedBracketsUsingDeque balancedBracketsUsingDeque;
@Before
@BeforeEach
public void setup() {
balancedBracketsUsingDeque = new BalancedBracketsUsingDeque();
}
@Test
public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() {
void givenNullInput_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced(null);
assertThat(result).isFalse();
}
@Test
public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() {
void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingDeque.isBalanced("");
assertThat(result).isTrue();
}
@Test
public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() {
void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("abc[](){}");
assertThat(result).isFalse();
}
@Test
public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() {
void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}");
assertThat(result).isFalse();
}
@Test
public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() {
void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}}");
assertThat(result).isFalse();
}
@Test
public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{[(])}");
assertThat(result).isFalse();
}
@Test
public void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{}(");
assertThat(result).isFalse();
}
@Test
public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() {
void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingDeque.isBalanced("{[()]}");
assertThat(result).isTrue();
}
@Test
public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() {
void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{[[(())]]}}");
assertThat(result).isTrue();
}
@Test
public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() {
void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{([])}}");
assertThat(result).isTrue();
}
@Test
public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() {
void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingDeque.isBalanced("{{)[](}}");
assertThat(result).isFalse();
}

View File

@ -1,80 +1,81 @@
package com.baeldung.algorithms.balancedbrackets;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BalancedBracketsUsingStringUnitTest {
class BalancedBracketsUsingStringUnitTest {
private BalancedBracketsUsingString balancedBracketsUsingString;
@Before
@BeforeEach
public void setup() {
balancedBracketsUsingString = new BalancedBracketsUsingString();
}
@Test
public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() {
void givenNullInput_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced(null);
assertThat(result).isFalse();
}
@Test
public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() {
void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingString.isBalanced("");
assertThat(result).isTrue();
}
@Test
public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() {
void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("abc[](){}");
assertThat(result).isFalse();
}
@Test
public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() {
void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}");
assertThat(result).isFalse();
}
@Test
public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() {
void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}}");
assertThat(result).isFalse();
}
@Test
public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{[(])}");
assertThat(result).isFalse();
}
@Test
public void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{{}(");
assertThat(result).isFalse();
}
@Test
public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() {
void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingString.isBalanced("{[()]}");
assertThat(result).isTrue();
}
@Test
public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() {
void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingString.isBalanced("{{[[(())]]}}");
assertThat(result).isTrue();
}
@Test
public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() {
void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() {
boolean result = balancedBracketsUsingString.isBalanced("{{([])}}");
assertThat(result).isTrue();
}
@Test
public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() {
void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() {
boolean result = balancedBracketsUsingString.isBalanced("{{)[](}}");
assertThat(result).isFalse();
}

View File

@ -2,17 +2,17 @@ package com.baeldung.algorithms.boruvka;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.google.common.graph.MutableValueGraph;
import com.google.common.graph.ValueGraphBuilder;
public class BoruvkaUnitTest {
class BoruvkaUnitTest {
private MutableValueGraph<Integer, Integer> graph;
@Before
@BeforeEach
public void setup() {
graph = ValueGraphBuilder.undirected()
.build();
@ -26,7 +26,7 @@ public class BoruvkaUnitTest {
}
@Test
public void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() {
void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() {
BoruvkaMST boruvkaMST = new BoruvkaMST(graph);
MutableValueGraph<Integer, Integer> mst = boruvkaMST.getMST();

View File

@ -1,15 +1,15 @@
package com.baeldung.algorithms.gradientdescent;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.function.Function;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class GradientDescentUnitTest {
class GradientDescentUnitTest {
@Test
public void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() {
void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() {
Function<Double, Double> df = x ->
StrictMath.abs(StrictMath.pow(x, 3)) - (3 * StrictMath.pow(x, 2)) + x;
GradientDescent gd = new GradientDescent();

View File

@ -1,13 +1,14 @@
package com.baeldung.algorithms.greedy;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class GreedyAlgorithmUnitTest {
class GreedyAlgorithmUnitTest {
private SocialConnector prepareNetwork() {
SocialConnector sc = new SocialConnector();
@ -35,21 +36,21 @@ public class GreedyAlgorithmUnitTest {
}
@Test
public void greedyAlgorithmTest() {
void greedyAlgorithmTest() {
GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork());
assertEquals(ga.findMostFollowersPath("root"), 5);
}
@Test
public void nongreedyAlgorithmTest() {
void nongreedyAlgorithmTest() {
NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0);
Assertions.assertThrows(IllegalStateException.class, () -> {
assertThrows(IllegalStateException.class, () -> {
nga.findMostFollowersPath("root");
});
}
@Test
public void nongreedyAlgorithmUnboundedTest() {
void nongreedyAlgorithmUnboundedTest() {
SocialConnector sc = prepareNetwork();
sc.switchCounter();
NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0);

View File

@ -1,21 +1,23 @@
package com.baeldung.algorithms.kruskal;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.google.common.graph.MutableValueGraph;
import com.google.common.graph.ValueGraph;
import com.google.common.graph.ValueGraphBuilder;
import com.baeldung.algorithms.kruskal.Kruskal;
public class KruskalUnitTest {
class KruskalUnitTest {
private MutableValueGraph<Integer, Double> graph;
@Before
@BeforeEach
public void setup() {
graph = ValueGraphBuilder.undirected().build();
graph.putEdgeValue(0, 1, 8.0);
@ -28,7 +30,7 @@ public class KruskalUnitTest {
}
@Test
public void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() {
void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() {
final Kruskal kruskal = new Kruskal();
ValueGraph<Integer, Double> spanningTree = kruskal.minSpanningTree(graph);
@ -47,7 +49,7 @@ public class KruskalUnitTest {
}
@Test
public void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() {
void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() {
final Kruskal kruskal = new Kruskal();
ValueGraph<Integer, Double> spanningTree = kruskal.maxSpanningTree(graph);

View File

@ -1,13 +1,13 @@
package com.baeldung.algorithms.linkedlist;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.jupiter.api.Test;
public class LinkedListReversalUnitTest {
class LinkedListReversalUnitTest {
@Test
public void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() {
void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() {
ListNode head = constructLinkedList();
ListNode node = head;
for (int i = 1; i <= 5; i++) {
@ -25,7 +25,7 @@ public class LinkedListReversalUnitTest {
}
@Test
public void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() {
void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() {
ListNode head = constructLinkedList();
ListNode node = head;
for (int i = 1; i <= 5; i++) {

View File

@ -2,17 +2,17 @@ package com.baeldung.algorithms.minheapmerge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class MinHeapUnitTest {
class MinHeapUnitTest {
private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } };
private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 };
@Test
public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() {
void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() {
int[] resultArray = MinHeap.merge(inputArray);
assertThat(resultArray.length, is(equalTo(10)));

View File

@ -1,13 +1,13 @@
package com.baeldung.algorithms.topkelements;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class TopKElementsFinderUnitTest {
import org.junit.jupiter.api.Test;
class TopKElementsFinderUnitTest {
private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder();
private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder();
private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder();
@ -20,27 +20,27 @@ public class TopKElementsFinderUnitTest {
@Test
public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() {
void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() {
assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
}
@Test
public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
}
@Test
public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
}
}

View File

@ -1,63 +1,66 @@
package com.baeldung.algorithms.luhn;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class LuhnCheckerUnitTest {
import org.junit.jupiter.api.Test;
class LuhnCheckerUnitTest {
@Test
public void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() {
void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() {
String cardNumber = "8649";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
assertTrue(result);
}
@Test
public void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() {
void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() {
String cardNumber = "8642";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
assertFalse(result);
}
@Test
public void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() {
void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "0505050505050505";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
assertTrue(result);
}
@Test
public void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() {
void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() {
String cardNumber = "75757575757575";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertTrue(result);
assertTrue(result);
}
@Test
public void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() {
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(0), 0);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(1), 2);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(2), 4);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(3), 6);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(4), 8);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(5), 1);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(6), 3);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(7), 5);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(8), 7);
Assert.assertEquals(LuhnChecker.doubleAndSumDigits(9), 9);
void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() {
assertEquals(0,LuhnChecker.doubleAndSumDigits(0));
assertEquals(2,LuhnChecker.doubleAndSumDigits(1));
assertEquals(4, LuhnChecker.doubleAndSumDigits(2));
assertEquals(6, LuhnChecker.doubleAndSumDigits(3));
assertEquals(8, LuhnChecker.doubleAndSumDigits(4));
assertEquals(1, LuhnChecker.doubleAndSumDigits(5));
assertEquals(3, LuhnChecker.doubleAndSumDigits(6));
assertEquals(5, LuhnChecker.doubleAndSumDigits(7));
assertEquals(7, LuhnChecker.doubleAndSumDigits(8));
assertEquals(9, LuhnChecker.doubleAndSumDigits(9));
}
@Test
public void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() {
void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() {
String cardNumber = "test";
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
assertFalse(result);
}
@Test
public void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() {
void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() {
String cardNumber = null;
boolean result = LuhnChecker.checkLuhn(cardNumber);
Assert.assertFalse(result);
assertFalse(result);
}
}

View File

@ -1,11 +1,13 @@
package com.baeldung.algorithms.binarysearch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class BinarySearchUnitTest {
import org.junit.jupiter.api.Test;
class BinarySearchUnitTest {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
@ -15,27 +17,27 @@ public class BinarySearchUnitTest {
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
}
@Test
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
}
}

View File

@ -1,15 +1,15 @@
package com.baeldung.algorithms.dfs;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class BinaryTreeUnitTest {
class BinaryTreeUnitTest {
@Test
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
BinaryTree bt = createBinaryTree();
@ -17,7 +17,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
BinaryTree bt = createBinaryTree();
@ -28,7 +28,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() {
void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() {
BinaryTree bt = createBinaryTree();
@ -40,7 +40,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() {
void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() {
BinaryTree bt = createBinaryTree();
@ -48,7 +48,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
BinaryTree bt = createBinaryTree();
@ -58,7 +58,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() {
void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() {
BinaryTree bt = createBinaryTree();
@ -71,7 +71,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void it_deletes_the_root() {
void it_deletes_the_root() {
int value = 12;
BinaryTree bt = new BinaryTree();
bt.add(value);
@ -82,7 +82,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
BinaryTree bt = createBinaryTree();
@ -92,7 +92,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
BinaryTree bt = createBinaryTree();
@ -102,7 +102,7 @@ public class BinaryTreeUnitTest {
}
@Test
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
BinaryTree bt = createBinaryTree();

View File

@ -2,12 +2,12 @@ package com.baeldung.algorithms.dfs;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class GraphUnitTest {
class GraphUnitTest {
@Test
public void givenDirectedGraph_whenDFS_thenPrintAllValues() {
void givenDirectedGraph_whenDFS_thenPrintAllValues() {
Graph graph = createDirectedGraph();
graph.dfs(0);
System.out.println();
@ -15,7 +15,7 @@ public class GraphUnitTest {
}
@Test
public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
Graph graph = createDirectedGraph();
List<Integer> list = graph.topologicalSort(0);
System.out.println(list);

View File

@ -1,27 +1,28 @@
package com.baeldung.algorithms.interpolationsearch;
import org.junit.Before;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class InterpolationSearchUnitTest {
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class InterpolationSearchUnitTest {
private int[] myData;
@Before
@BeforeEach
public void setUp() {
myData = new int[]{13,21,34,55,69,73,84,101};
}
@Test
public void givenSortedArray_whenLookingFor84_thenReturn6() {
void givenSortedArray_whenLookingFor84_thenReturn6() {
int pos = InterpolationSearch.interpolationSearch(myData, 84);
assertEquals(6, pos);
}
@Test
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
int pos = InterpolationSearch.interpolationSearch(myData, 19);
assertEquals(-1, pos);
}

View File

@ -9,13 +9,13 @@ import java.util.*;
import static com.baeldung.algorithms.kthsmallest.KthSmallest.*;
import static org.junit.jupiter.api.Assertions.*;
public class KthSmallestUnitTest {
class KthSmallestUnitTest {
@Nested
class Exceptions {
@Test
public void when_at_least_one_list_is_null_then_an_exception_is_thrown() {
void when_at_least_one_list_is_null_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, null, null);
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null);
@ -27,7 +27,7 @@ public class KthSmallestUnitTest {
}
@Test
public void when_at_least_one_list_is_empty_then_an_exception_is_thrown() {
void when_at_least_one_list_is_empty_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2});
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{});
@ -39,19 +39,19 @@ public class KthSmallestUnitTest {
}
@Test
public void when_k_is_smaller_than_0_then_an_exception_is_thrown() {
void when_k_is_smaller_than_0_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
}
@Test
public void when_k_is_smaller_than_1_then_an_exception_is_thrown() {
void when_k_is_smaller_than_1_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
}
@Test
public void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() {
void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5});
assertThrows(NoSuchElementException.class, executable1);
}

View File

@ -1,12 +1,13 @@
package com.baeldung.algorithms.mcts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
import com.baeldung.algorithms.mcts.montecarlo.State;
@ -15,31 +16,31 @@ import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position;
import com.baeldung.algorithms.mcts.tree.Tree;
public class MCTSUnitTest {
class MCTSUnitTest {
private Tree gameTree;
private MonteCarloTreeSearch mcts;
@Before
@BeforeEach
public void initGameTree() {
gameTree = new Tree();
mcts = new MonteCarloTreeSearch();
}
@Test
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
double uctValue = 15.79;
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
}
@Test
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
State initState = gameTree.getRoot().getState();
List<State> possibleStates = initState.getAllPossibleStates();
assertTrue(possibleStates.size() > 0);
}
@Test
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
Board board = new Board();
int initAvailablePositions = board.getEmptyPositions().size();
board.performMove(Board.P1, new Position(1, 1));
@ -48,7 +49,7 @@ public class MCTSUnitTest {
}
@Test
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
Board board = new Board();
int player = Board.P1;
@ -61,11 +62,11 @@ public class MCTSUnitTest {
player = 3 - player;
}
int winStatus = board.checkStatus();
assertEquals(winStatus, Board.DRAW);
assertEquals(Board.DRAW, winStatus);
}
@Test
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
Board board = new Board();
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
mcts1.setLevel(1);

View File

@ -1,21 +1,22 @@
package com.baeldung.algorithms.quadtree;
import org.junit.Assert;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class QuadTreeSearchUnitTest {
class QuadTreeSearchUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(QuadTreeSearchUnitTest.class);
private static QuadTree quadTree;
@BeforeClass
@BeforeAll
public static void setUp() {
Region area = new Region(0, 0, 400, 400);
quadTree = new QuadTree(area);
@ -32,30 +33,30 @@ public class QuadTreeSearchUnitTest {
}
@Test
public void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() {
void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() {
Region searchArea = new Region(200, 200, 250, 250);
List<Point> result = quadTree.search(searchArea, null, "");
LOGGER.debug(result.toString());
LOGGER.debug(quadTree.printSearchTraversePath());
Assert.assertEquals(1, result.size());
Assert.assertArrayEquals(new float[] { 245, 238 },
assertEquals(1, result.size());
assertArrayEquals(new float[] { 245, 238 },
new float[]{result.get(0).getX(), result.get(0).getY() }, 0);
}
@Test
public void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() {
void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() {
Region searchArea = new Region(0, 0, 100, 100);
List<Point> result = quadTree.search(searchArea, null, "");
LOGGER.debug(result.toString());
LOGGER.debug(quadTree.printSearchTraversePath());
Assert.assertEquals(2, result.size());
Assert.assertArrayEquals(new float[] { 21, 25 },
assertEquals(2, result.size());
assertArrayEquals(new float[] { 21, 25 },
new float[]{result.get(0).getX(), result.get(0).getY() }, 0);
Assert.assertArrayEquals(new float[] { 55, 53 },
assertArrayEquals(new float[] { 55, 53 },
new float[]{result.get(1).getX(), result.get(1).getY() }, 0);
}

View File

@ -1,71 +1,72 @@
package com.baeldung.algorithms.suffixtree;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.List;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SuffixTreeUnitTest {
class SuffixTreeUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTreeUnitTest.class);
private static SuffixTree suffixTree;
@BeforeClass
@BeforeAll
public static void setUp() {
suffixTree = new SuffixTree("havanabanana");
printTree();
}
@Test
public void givenSuffixTree_whenSearchingForA_thenReturn6Matches() {
void givenSuffixTree_whenSearchingForA_thenReturn6Matches() {
List<String> matches = suffixTree.searchText("a");
matches.stream()
.forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] { "h[a]vanabanana", "hav[a]nabanana", "havan[a]banana", "havanab[a]nana", "havanaban[a]na", "havanabanan[a]" }, matches.toArray());
assertArrayEquals(new String[] { "h[a]vanabanana", "hav[a]nabanana", "havan[a]banana", "havanab[a]nana", "havanaban[a]na", "havanabanan[a]" }, matches.toArray());
}
@Test
public void givenSuffixTree_whenSearchingForNab_thenReturn1Match() {
void givenSuffixTree_whenSearchingForNab_thenReturn1Match() {
List<String> matches = suffixTree.searchText("nab");
matches.stream()
.forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] { "hava[nab]anana" }, matches.toArray());
assertArrayEquals(new String[] { "hava[nab]anana" }, matches.toArray());
}
@Test
public void givenSuffixTree_whenSearchingForNag_thenReturnNoMatches() {
void givenSuffixTree_whenSearchingForNag_thenReturnNoMatches() {
List<String> matches = suffixTree.searchText("nag");
matches.stream()
.forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] {}, matches.toArray());
assertArrayEquals(new String[] {}, matches.toArray());
}
@Test
public void givenSuffixTree_whenSearchingForBanana_thenReturn2Matches() {
void givenSuffixTree_whenSearchingForBanana_thenReturn2Matches() {
List<String> matches = suffixTree.searchText("ana");
matches.stream()
.forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] { "hav[ana]banana", "havanab[ana]na", "havanaban[ana]" }, matches.toArray());
assertArrayEquals(new String[] { "hav[ana]banana", "havanab[ana]na", "havanaban[ana]" }, matches.toArray());
}
@Test
public void givenSuffixTree_whenSearchingForNa_thenReturn4Matches() {
void givenSuffixTree_whenSearchingForNa_thenReturn4Matches() {
List<String> matches = suffixTree.searchText("na");
matches.stream()
.forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] { "hava[na]banana", "havanaba[na]na", "havanabana[na]" }, matches.toArray());
assertArrayEquals(new String[] { "hava[na]banana", "havanaba[na]na", "havanabana[na]" }, matches.toArray());
}
@Test
public void givenSuffixTree_whenSearchingForX_thenReturnNoMatches() {
void givenSuffixTree_whenSearchingForX_thenReturnNoMatches() {
List<String> matches = suffixTree.searchText("x");
matches.stream()
.forEach(m -> LOGGER.debug(m));
Assert.assertArrayEquals(new String[] {}, matches.toArray());
assertArrayEquals(new String[] {}, matches.toArray());
}
private static void printTree() {

View File

@ -1,23 +1,24 @@
package com.baeldung.algorithms.textsearch;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class TextSearchAlgorithmsUnitTest {
class TextSearchAlgorithmsUnitTest {
@Test
public void testStringSearchAlgorithms() {
void testStringSearchAlgorithms() {
String text = "This is some nice text.";
String pattern = "some";
int realPosition = text.indexOf(pattern);
Assert.assertTrue(realPosition == TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
assertEquals(TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()), realPosition);
assertEquals(TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()), realPosition);
assertEquals(TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()) , realPosition);
assertEquals(TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()), realPosition);
assertEquals(TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()), realPosition);
}
}

View File

@ -1,17 +1,19 @@
package com.baeldung.algorithms.bynumber;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.jupiter.api.Test;
public class NaturalOrderComparatorsUnitTest {
class NaturalOrderComparatorsUnitTest {
@Test
public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
@ -25,7 +27,7 @@ public class NaturalOrderComparatorsUnitTest {
}
@Test
public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
@ -39,7 +41,7 @@ public class NaturalOrderComparatorsUnitTest {
}
@Test
public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
@ -53,7 +55,7 @@ public class NaturalOrderComparatorsUnitTest {
}
@Test
public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
@ -66,7 +68,7 @@ public class NaturalOrderComparatorsUnitTest {
}
@Test
public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
List<String> testStrings = Arrays.asList("a", "c", "d", "e");
List<String> expected = new ArrayList<>(testStrings);

View File

@ -1,15 +1,16 @@
package com.baeldung.algorithms.gravitysort;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class GravitySortUnitTest {
import org.junit.jupiter.api.Test;
class GravitySortUnitTest {
@Test
public void givenIntegerArray_whenSortedWithGravitySort_thenGetSortedArray() {
void givenIntegerArray_whenSortedWithGravitySort_thenGetSortedArray() {
int[] actual = { 9, 9, 100, 3, 57, 12, 3, 78, 0, 2, 2, 40, 21, 9 };
int[] expected = { 0, 2, 2, 3, 3, 9, 9, 9, 12, 21, 40, 57, 78, 100 };
GravitySort.sort(actual);
Assert.assertArrayEquals(expected, actual);
assertArrayEquals(expected, actual);
}
}

View File

@ -1,23 +1,22 @@
package com.baeldung.algorithms.inoutsort;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class InOutSortUnitTest {
class InOutSortUnitTest {
@Test
public void givenArray_whenInPlaceSort_thenReversed() {
void givenArray_whenInPlaceSort_thenReversed() {
int[] input = {1, 2, 3, 4, 5, 6, 7};
int[] expected = {7, 6, 5, 4, 3, 2, 1};
assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseInPlace(input));
assertArrayEquals(expected, InOutSort.reverseInPlace(input), "the two arrays are not equal");
}
@Test
public void givenArray_whenOutOfPlaceSort_thenReversed() {
void givenArray_whenOutOfPlaceSort_thenReversed() {
int[] input = {1, 2, 3, 4, 5, 6, 7};
int[] expected = {7, 6, 5, 4, 3, 2, 1};
assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseOutOfPlace(input));
assertArrayEquals(expected, InOutSort.reverseOutOfPlace(input), "the two arrays are not equal");
}
}

View File

@ -1,16 +1,17 @@
package com.baeldung.algorithms.quicksort;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class BentleyMcilroyPartitioningUnitTest {
import org.junit.jupiter.api.Test;
class BentleyMcilroyPartitioningUnitTest {
@Test
public void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() {
void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() {
int[] actual = {3, 2, 2, 2, 3, 7, 7, 3, 2, 2, 7, 3, 3};
int[] expected = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 7, 7};
BentleyMcIlroyPartioning.quicksort(actual, 0, actual.length - 1);
Assert.assertArrayEquals(expected, actual);
assertArrayEquals(expected, actual);
}
}

View File

@ -1,15 +1,16 @@
package com.baeldung.algorithms.quicksort;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class DNFThreeWayQuickSortUnitTest {
import org.junit.jupiter.api.Test;
class DNFThreeWayQuickSortUnitTest {
@Test
public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() {
void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() {
int[] actual = {3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3};
int[] expected = {3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7};
DutchNationalFlagPartioning.quicksort(actual, 0, actual.length - 1);
Assert.assertArrayEquals(expected, actual);
assertArrayEquals(expected, actual);
}
}

View File

@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class BubbleSortUnitTest {
class BubbleSortUnitTest {
@Test
public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() {
void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() {
Integer[] array = { 2, 1, 4, 6, 3, 5 };
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
BubbleSort bubbleSort = new BubbleSort();
@ -16,7 +16,7 @@ public class BubbleSortUnitTest {
}
@Test
public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() {
void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() {
Integer[] array = { 2, 1, 4, 6, 3, 5 };
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
BubbleSort bubbleSort = new BubbleSort();

View File

@ -1,24 +1,26 @@
package com.baeldung.algorithms.bucketsort;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class IntegerBucketSorterUnitTest {
class IntegerBucketSorterUnitTest {
private IntegerBucketSorter sorter;
@Before
@BeforeEach
public void setUp() throws Exception {
sorter = new IntegerBucketSorter();
}
@Test
public void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() {
void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() {
List<Integer> unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15);
List<Integer> expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602);
@ -26,7 +28,5 @@ public class IntegerBucketSorterUnitTest {
List<Integer> actual = sorter.sort(unsorted);
assertEquals(expected, actual);
}
}

View File

@ -1,16 +1,16 @@
package com.baeldung.algorithms.heapsort;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class HeapUnitTest {
class HeapUnitTest {
@Test
public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() {
void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() {
// given
Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2);
@ -22,7 +22,7 @@ public class HeapUnitTest {
}
@Test
public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() {
void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() {
// given
List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2);

View File

@ -1,25 +1,25 @@
package com.baeldung.algorithms.insertionsort;
import com.baeldung.algorithms.insertionsort.InsertionSort;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class InsertionSortUnitTest {
import org.junit.jupiter.api.Test;
class InsertionSortUnitTest {
@Test
public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() {
void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() {
int[] input = {6, 2, 3, 4, 5, 1};
InsertionSort.insertionSortImperative(input);
int[] expected = {1, 2, 3, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input);
assertArrayEquals(expected, input, "the two arrays are not equal");
}
@Test
public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() {
void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() {
int[] input = {6, 4, 5, 2, 3, 1};
InsertionSort.insertionSortRecursive(input);
int[] expected = {1, 2, 3, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input);
assertArrayEquals( expected, input, "the two arrays are not equal");
}
}

View File

@ -1,17 +1,17 @@
package com.baeldung.algorithms.mergesort;
import org.junit.Assert;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class MergeSortUnitTest {
class MergeSortUnitTest {
@Test
public void positiveTest() {
void positiveTest() {
int[] actual = { 5, 1, 6, 2, 3, 4 };
int[] expected = { 1, 2, 3, 4, 5, 6 };
MergeSort.mergeSort(actual, actual.length);
Assert.assertArrayEquals(expected, actual);
assertArrayEquals(expected, actual);
}
}

View File

@ -1,17 +1,17 @@
package com.baeldung.algorithms.quicksort;
import com.baeldung.algorithms.quicksort.QuickSort;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class QuickSortUnitTest {
import org.junit.jupiter.api.Test;
class QuickSortUnitTest {
@Test
public void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() {
void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() {
int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 };
int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
QuickSort.quickSort(actual, 0, actual.length-1);
Assert.assertArrayEquals(expected, actual);
assertArrayEquals(expected, actual);
}
}

View File

@ -1,15 +1,16 @@
package com.baeldung.algorithms.quicksort;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class ThreeWayQuickSortUnitTest {
import org.junit.jupiter.api.Test;
class ThreeWayQuickSortUnitTest {
@Test
public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() {
int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 };
int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 };
ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1);
Assert.assertArrayEquals(expected, actual);
assertArrayEquals(expected, actual);
}
}

View File

@ -1,13 +1,13 @@
package com.baeldung.algorithms.radixsort;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class RadixSortUnitTest {
class RadixSortUnitTest {
@Test
public void givenUnsortedArray_whenRadixSort_thenArraySorted() {
void givenUnsortedArray_whenRadixSort_thenArraySorted() {
int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 };
RadixSort.sort(numbers);
int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 };

View File

@ -1,25 +1,24 @@
package com.baeldung.algorithms.selectionsort;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class SelectionSortUnitTest {
class SelectionSortUnitTest {
@Test
public void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() {
void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() {
int[] input = { 5, 4, 1, 6, 2 };
SelectionSort.sortAscending(input);
int[] expected = {1, 2, 4, 5, 6};
assertArrayEquals("the two arrays are not equal", expected, input);
assertArrayEquals(expected, input, "the two arrays are not equal");
}
@Test
public void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() {
void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() {
int[] input = { 5, 4, 1, 6, 2 };
SelectionSort.sortDescending(input);
int[] expected = {6, 5, 4, 2, 1};
assertArrayEquals("the two arrays are not equal", expected, input);
assertArrayEquals(expected, input, "the two arrays are not equal");
}
}

View File

@ -1,17 +1,17 @@
package com.baeldung.algorithms.shellsort;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class ShellSortUnitTest {
import org.junit.jupiter.api.Test;
class ShellSortUnitTest {
@Test
public void givenUnsortedArray_whenShellSort_thenSortedAsc() {
void givenUnsortedArray_whenShellSort_thenSortedAsc() {
int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
ShellSort.sort(input);
int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
assertArrayEquals("the two arrays are not equal", expected, input);
assertArrayEquals( expected, input, "the two arrays are not equal");
}
}

View File

@ -330,8 +330,6 @@
<module>parent-spring-5</module>
<module>parent-java</module>
<module>algorithms-modules</module>
<module>apache-cxf-modules</module>
<module>apache-libraries</module>
<module>apache-poi</module>
@ -615,8 +613,6 @@
<module>parent-spring-5</module>
<module>parent-java</module>
<module>algorithms-modules</module>
<module>apache-cxf-modules</module>
<module>apache-libraries</module>
<module>apache-poi</module>
@ -912,6 +908,7 @@
</build>
<modules>
<module>algorithms-modules</module>
<module>core-java-modules/core-java-9</module>
<module>core-java-modules/core-java-9-improvements</module>
<module>core-java-modules/core-java-9-jigsaw</module>
@ -1108,6 +1105,7 @@
</build>
<modules>
<module>algorithms-modules</module>
<module>core-java-modules/core-java-9</module>
<module>core-java-modules/core-java-9-improvements</module>
<module>core-java-modules/core-java-9-jigsaw</module>