JAVA的單元測試技術


1.選定開發工具

選定eclipse為開發工具,用JAVA進行編程,實現此次測試。

![](https://img2018.cnblogs.com/blog/1644765/201904/1644765-20190412222343264-1779774141.png)

2.編寫需要被測試的java類

此次我們以順序查找與二分查找法為例。

package com.mycode.tuils;

public class Search {
	
	public int sqlSearch(int a,int[] arr,int b)  //順序查找
	{
		int i;
		for(i=0;i<arr.length;i++)
		{
			if(a==arr[i])
			{ 
				b=i;
				break;
			}
		}
		return b;
	}
	
	public int binarySearch(int a,int[] arr,int b)  //二分查找法("arr"為排序[升序]過后的數組)
	{
		int low=0;
		int high=arr.length-1;
		int mid;
		while(low<=high)
		{
			mid = (low + high)/2;
			if (arr[mid] == a)
			{
				b = mid;
				break;
			}
			else if (arr[mid] < a)
				low = mid + 1;
			else if (arr[mid] > a)
				high = mid - 1;
			
		}
		return b;
	}
       
}

3.創建測試單元

(1)右鍵點擊新建的project,選定Build Path->Add Library->JUnit->JUnit5
(2)創建新的Sound folder,命名為test(src->Sound floder)
(3)自動生成測試類,選定編寫的被測試類Search()->NEW->orther
(4)點開orther,在Wizard中搜索JUnit->JUnit Test Case,如下圖所示,修改圖中紅色標記處。

![](https://img2018.cnblogs.com/blog/1644765/201904/1644765-20190413161206264-1981526342.jpg)

(5)點擊下一步,選定所有被測試函數->Finish。

![](https://img2018.cnblogs.com/blog/1644765/201904/1644765-20190413161507742-1783102241.png)

4.編寫測試類

package com.mycode.tuils;

import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class SearchAutoTest {

	@Test
	public void sqlSearch()
	{
		int[] arr= {1,5,8,6,11,25,36,42,15,85};
		int a=8;
		int b=0;
		int c=2;
		assertEquals(c,new Search().sqlSearch(a,arr,b));
		
	}
	
	@Test
	public void binarySearch()
	{
		int[] arr= {1,5,6,8,11,15,25,36,42,85};
		assertEquals(3,new Search().binarySearch(8,arr,0));
	}
}

5.運行測試類

選定測試類->Run As->JUnit Test

##6.測試結果

當Errors=0,與Failures=0,以及所有函數運行成功時說明此次測試成功。如下圖所示。

![](https://img2018.cnblogs.com/blog/1644765/201904/1644765-20190413152833361-1223695564.png)
###注意:

(1)每個測試函數前加@Test,以保證測試可以正常運行。
(2)測試類與被測試類所在的包的名字必須相同。
(3)編寫被測試代碼時先寫主函數,保證程序的正常運行,在測試前再刪除主函數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM