# 基于二分查找的Junit测试实验

1.二分查找函数

 public int BinarySearch(int sorted[],int key){
int left = 0;
int right = sorted.length - 1;
// 这里必须是 <=
while (left < right) {
//计算中间位置
int mid = (left + right) / 2;
if (sorted[mid] == key) {
return mid;
}
else if (sorted[mid] < key) {
left = mid + 1;
}
else {
right = mid - 1;
}
}

return -1;
}

（BinarySearch函数）

2.流程控制图

3.控制流图

4.实际测试

    @Test
public void Test1(){
System.out.println("100%语句覆盖");
int sorted[]=new int[]{1,2,3};
int key1=0;
int key2=1;
int key3=3;
BinarySearch(sorted,key1);
BinarySearch(sorted,key2);
BinarySearch(sorted,key3);
}
@Test
public void Test2(){
System.out.println("完全分支覆盖");
int sorted[]=new int[]{1,2,3,4,5,6,7,8,9};
int key1=0;
int key2=6;
BinarySearch(sorted,key1);
BinarySearch(sorted,key2);
}
@Test
public void Test3(){
System.out.println("完全谓词覆盖");
int sorted[]=new int[]{1,2,3,4,5,6,7,8,9};
int key1=0;
int key2=6;
BinarySearch(sorted,key1);
BinarySearch(sorted,key2);
}

（测试代码）
①路径谓词表达式:
1).left>right
2). {left<=right,sorted[mid]!=key, sorted[mid]>key, left<=right ,sorted[mid]==key}
3). {left<=right,sorted[mid]!=key, sorted[mid]<key, left<=right ,sorted[mid]==key}
② 路径谓词表达式:
1).left>right
2). {left<=right,sorted[mid]!=key, sorted[mid]>key, left<=right ,sorted[mid]==key}
3). {left<=right,sorted[mid]!=key, sorted[mid]<key, left<=right ,sorted[mid]==key}

③ 路径谓词表达式:
1).left>right
2). {left<=right,sorted[mid]!=key, sorted[mid]>key, left<=right ,sorted[mid]==key}
3). {left<=right,sorted[mid]!=key, sorted[mid]<key, left<=right ,sorted[mid]==key}

4.引入缺陷 第15行left

@Test
public void Test4(){
System.out.println("缺陷");
int sorted[]=new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
int key1=11;
System.out.println(BinarySearch(sorted,key1));
}


5.解决缺陷,查找缺陷

@Test
public void Test5(){
System.out.println("缺陷");
int sorted[]=new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
System.out.println(BinarySearch(sorted,0));
for (int i: sorted) {
System.out.println(BinarySearch(sorted,i));
}
}