Update BinarySearchTest.java

master
wangsiyuan 2024-07-10 00:31:05 +08:00
parent 4f478c08ac
commit 35e5acb50f
1 changed files with 37 additions and 1 deletions

View File

@ -2,12 +2,14 @@ package com.nbee.solution.practice;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BinarySearchTest {
private int[] nums = {1, 3, 5, 7, 9};
@Test
public void testBinarySearchBasic_Found() {
int[] nums = {1, 3, 5, 7, 9};
int[] nums = {1, 3, 5, 7, 9, 11, 13};
int target = 5;
int result = BinarySearch.binarySearchBasic(nums, target);
Assert.assertEquals("Element should be found at index 2", 2, result);
@ -48,4 +50,38 @@ public class BinarySearchTest {
int result = BinarySearch.binarySearchBasic(nums, target);
Assert.assertEquals("Binary search should work on decreasing arrays", 2, result);
}
@Test
public void testBinarySearchAlternativeFound() {
// Test that the method correctly returns the index of an existing element
int target = 7;
int result = BinarySearch.binarySearchAlternative(nums, target);
assertEquals(3, result, "The target should be found at index 3");
}
@Test
public void testBinarySearchAlternativeNotFound() {
// Test that the method correctly returns -1 when the element is not present
int target = 4;
int result = BinarySearch.binarySearchAlternative(nums, target);
assertEquals(-1, result, "The target should not be found");
}
@Test
public void testBinarySearchAlternativeWithEmptyArray() {
// Test with an empty array
int[] emptyNums = new int[]{};
int target = 1;
int result = BinarySearch.binarySearchAlternative(emptyNums, target);
assertEquals(-1, result, "The target should not be found in an empty array");
}
@Test
public void testBinarySearchAlternativeWithSingleElement() {
// Test with a single element array
int[] singleNums = new int[]{5};
int target = 5;
int result = BinarySearch.binarySearchAlternative(singleNums, target);
assertEquals(0, result, "The target should be found at index 0 in a single-element array");
}
}