- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathBreadthFirstSearchTest.java
104 lines (81 loc) · 2.91 KB
/
BreadthFirstSearchTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
packagecom.thealgorithms.searches;
importstaticorg.junit.jupiter.api.Assertions.assertArrayEquals;
importstaticorg.junit.jupiter.api.Assertions.assertEquals;
importstaticorg.junit.jupiter.api.Assertions.assertTrue;
importcom.thealgorithms.datastructures.Node;
importjava.util.List;
importjava.util.Optional;
importorg.junit.jupiter.api.BeforeEach;
importorg.junit.jupiter.api.Test;
publicclassBreadthFirstSearchTest {
privateNode<String> root;
privateBreadthFirstSearch<String> bfs;
// Tree structure:
//
// A
// / | \
// B C D
// / \
// E F
@BeforeEach
publicvoidsetUp() {
// nodes declaration
root = newNode<>("A");
varnodeB = newNode<>("B");
varnodeC = newNode<>("C");
varnodeD = newNode<>("D");
varnodeE = newNode<>("E");
varnodeF = newNode<>("F");
// tree initialization
root.addChild(nodeB);
root.addChild(nodeC);
root.addChild(nodeD);
nodeB.addChild(nodeE);
nodeB.addChild(nodeF);
// create an instance to monitor the visited nodes
bfs = newBreadthFirstSearch<>();
}
@Test
publicvoidtestSearchRoot() {
StringexpectedValue = "A";
List<String> expectedPath = List.of("A");
// check value
Optional<Node<String>> value = bfs.search(root, expectedValue);
assertEquals(expectedValue, value.orElseGet(() -> newNode<>("")).getValue());
// check path
assertArrayEquals(expectedPath.toArray(), bfs.getVisited().toArray());
}
@Test
publicvoidtestSearchF() {
StringexpectedValue = "F";
List<String> expectedPath = List.of("A", "B", "C", "D", "E", "F");
// check value
Optional<Node<String>> value = Optional.of(bfs.search(root, expectedValue).orElseGet(() -> newNode<>(null)));
assertEquals(expectedValue, value.get().getValue());
// check path
assertArrayEquals(expectedPath.toArray(), bfs.getVisited().toArray());
}
@Test
voidtestSearchNull() {
List<String> expectedPath = List.of("A", "B", "C", "D", "E", "F");
Optional<Node<String>> node = bfs.search(root, null);
// check value
assertTrue(node.isEmpty());
// check path
assertArrayEquals(expectedPath.toArray(), bfs.getVisited().toArray());
}
@Test
voidtestNullRoot() {
varvalue = bfs.search(null, "B");
assertTrue(value.isEmpty());
}
@Test
voidtestSearchValueThatNotExists() {
List<String> expectedPath = List.of("A", "B", "C", "D", "E", "F");
varvalue = bfs.search(root, "Z");
// check that the value is empty because it's not exists in the tree
assertTrue(value.isEmpty());
// check path is the whole list
assertArrayEquals(expectedPath.toArray(), bfs.getVisited().toArray());
}
}