I have implemented Binary search code for a given sorted array, written unit test too, Please review my BST unit test code and let me know your comments for improvements.
class BinarySearch {
public int binSearch(int[] sortedArray, int key) {
return search(0, sortedArray.length - 1, key, sortedArray);
}
private static int search(int start, int end, int key, int[] sortedArray) {
int mid = start + ((end-start)/2);
if (mid >= start && mid <= end) {
if (sortedArray[mid] == key) {
return mid;
} else if (sortedArray[mid] > key) {
return search(start, mid-1, key, sortedArray);
} else if(sortedArray[mid] < key){
return search(mid+1, end, key, sortedArray);
}
}
return -1;
}
}
public class BinarySearchTest {
private BinarySearch binarySearchCUT;
private static final int UNSUCCESSFUL = -1;
@Before
public void setUp(){
binarySearchCUT = new BinarySearch();
}
@Test
public void testShouldReturnUnsuccessfulOnEmptyArray() {
assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{}, 0));
}
@Test
public void testShouldReturnUnsuccessfulOnLeftBound() {
assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 0));
}
@Test
public void testShouldReturnUnsuccessfulOnRightBound() {
assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 101));
}
@Test
public void testShouldReturnSuccessfulOnLeftBound() {
assertEquals(0, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 1));
}
@Test
public void testShouldReturnSuccessfulOnRightBound() {
assertEquals(12, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 100));
}
@Test
public void testShouldReturnSuccessfulOnMid() {
assertEquals(7, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 19));
}
@Test
public void testShouldReturnSuccessfulOnMidGreaterThanGivenNumber() {
assertEquals(5, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 12));
}
@Test
public void testShouldReturnSuccessfulOnMidLesserThanGivenNumber() {
assertEquals(10, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 69));
}
}
testSearch(int[] arr, int searchFor, int expected)and put your test-array into a constant. The individual tests would then just betestSeach(normArray, 4, normArray[4])much shorter to read and reason about. \$\endgroup\$Optionals. \$\endgroup\$