forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchTest.java
More file actions
85 lines (71 loc) · 2.43 KB
/
BinarySearchTest.java
File metadata and controls
85 lines (71 loc) · 2.43 KB
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
package com.thealgorithms.searches;
import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.IntStream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the BinarySearch class.
*/
class BinarySearchTest {
private final BinarySearch binarySearch = new BinarySearch();
@Test
@DisplayName("BinarySearch should find existing element")
void testBinarySearchFound() {
Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int key = 7;
assertEquals(6, binarySearch.find(array, key));
}
@Test
@DisplayName("BinarySearch should return -1 when element is not found")
void testBinarySearchNotFound() {
Integer[] array = {1, 2, 3, 4, 5};
int key = 6;
assertEquals(-1, binarySearch.find(array, key));
}
@Test
@DisplayName("BinarySearch should find first element")
void testBinarySearchFirstElement() {
Integer[] array = {1, 2, 3, 4, 5};
assertEquals(0, binarySearch.find(array, 1));
}
@Test
@DisplayName("BinarySearch should find last element")
void testBinarySearchLastElement() {
Integer[] array = {1, 2, 3, 4, 5};
assertEquals(4, binarySearch.find(array, 5));
}
@Test
@DisplayName("BinarySearch should handle single-element array (found)")
void testBinarySearchSingleElementFound() {
Integer[] array = {1};
assertEquals(0, binarySearch.find(array, 1));
}
@Test
@DisplayName("BinarySearch should handle single-element array (not found)")
void testBinarySearchSingleElementNotFound() {
Integer[] array = {1};
assertEquals(-1, binarySearch.find(array, 2));
}
@Test
@DisplayName("BinarySearch should return -1 for empty array")
void testBinarySearchEmptyArray() {
Integer[] array = {};
assertEquals(-1, binarySearch.find(array, 1));
}
@Test
@DisplayName("BinarySearch should handle large sorted array")
void testBinarySearchLargeArray() {
Integer[] array = IntStream.range(0, 10_000)
.boxed()
.toArray(Integer[]::new);
assertEquals(9999, binarySearch.find(array, 9999));
}
@Test
@DisplayName("BinarySearch should throw exception for null array")
void testBinarySearchNullArray() {
assertThrows(
IllegalArgumentException.class,
() -> binarySearch.find(null, 5)
);
}
}