1. 程式人生 > 其它 >3月22日筆記

3月22日筆記

Junit單元測試

測試分為黑盒測試和白盒測試,junit單元測試就是白盒測試。
測試的意義,就是查詢錯誤,我們寫的軟體規模很大時,可以用junit測試來查詢錯誤。
查詢錯誤,一種方法是寫個檔案,執行main函式,這樣很low,手擼程式碼速度慢,查詢錯誤的過程記錄下來的話需要的資源很多。

junit是一個框架,匯入方式如下:

 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

用法如下,在要測試的函式名前加@Test:

@Test
public void testAdd(){
  //測試內容
}

@Before註解修飾的的方法會在測試方法之前自動執行,被@After註解修飾的方法會在測試方法之後自定執行
所以,可以將最開始的初始化操作交給@Before,把最後的釋放資源操作交給@After。

@Before
public void setUp() throws Exception {
	System.out.println("this is brfore....");
}

@After
public void tearDown() throws Exception {
	System.out.println("this is after....");
}

@Test
public void test1() {
	System.out.println("this is test1....");
}	

我們關心的不是輸出結果,關心的是執行成功與否,也就是返回紅色或者綠色。
有一種“斷言”的機制,可以判斷執行的結果和我們期望的是否一致

@Test
public void testchu(){
	assertEquals(2,new Calculate().chu(6, 3));
        //assertEquals(期望值,程式實際執行結果);
}