1. 程式人生 > 實用技巧 >單元測試之道

單元測試之道

單元測試要求我們不僅要能寫出完成指定功能的程式碼,而且要能儘可能的測試程式碼是否符合預期標準,我們要對自己的專案完成耗時進行預估判斷,在整個的專案進行過程中對各個部分的時間進行合理規劃。

一、構建單元測試

  1. MSATest.java
 1 package com.company;
 2 import org.junit.Assert;
 3 import static org.junit.Assert.*;
 4 
 5 public class MSATest
 6 {
 7     @org.junit.Test
 8     public void calc()
 9     {
10 MSA msa = new MSA(); 11 int[][] arr={{4,-1,2,-2,3},{4,1,2,-3,-4}}; 12 int line0 = msa.Calc(arr,arr[0][0],0); 13 Assert.assertEquals(4,line0); 14 Assert.assertEquals(3,msa.getStart()); 15 Assert.assertEquals(1,msa.getEnd()); 16 int line1 = msa.Calc(arr,arr[1][0],1);
17 Assert.assertEquals(3,line1); 18 Assert.assertEquals(0,msa.getStart()); 19 Assert.assertEquals(1,msa.getEnd()); 20 } 21 }

2.ReadFileTest.java

 1 package com.company;
 2 
 3 import org.junit.Assert;
 4 import org.junit.Test;
 5 import static org.junit.Assert.*;
 6 
 7 public
class ReadFileTest 8 { 9 10 @Test 11 public void readFileByLines() 12 { 13 int arr[][] = new int[10][100]; 14 int[][] test={{4,-1,2,-2,3},{4,1,2,-3,-4}}; 15 int line = ReadFile.readFileByLines("src/com/company/arr.txt",arr); 16 //輸出讀取的陣列 17 for(int i=0; i<line; i++) 18 { 19 for(int j=1;j<=arr[i][0];j++) 20 { 21 Assert.assertEquals(test[i][j],arr[i][j]); 22 } 23 } 24 } 25 }


二、測試覆蓋率

(未完待續……)