junit淺學筆記二

來源:互聯網
上載者:User

   上一節初步介紹了什麼是單元測試,為什麼要做單元測試,以及junit4的初步使用,這裡我們接著說一下junit4中的註解。

  =============本節知識點============================

*     Error和Failures

*    Junit4 Annotation

==================================================================

 

1.   在講註解之前,先來認識 Error和Failures這兩種錯誤有什麼不同。

 

Errors:表示程式本身錯誤

 

 

@Test
publicvoid testAdd() {
int z=new T().add(5,3);
assertEquals(8,z);
int a=8/0; //這一句是有錯誤的
}

 

運行方法,會有一下錯誤提示:

Failures: 是指測試失敗。

@Test
publicvoid testAdd() {
int z=new T().add(5,4); //這裡修改了數值,把4該為3就正確了
assertEquals(8,z);
}

在來運行這個方法,看一下錯誤提示:

所以,我們在寫測試程式的時候,要先保證Errors是沒有錯誤的,再來看Failures有沒有錯誤。

 

2.  下面介紹junit4 的常用註解

-----------------------------------------------------------------------------------------------

*             @ Test:測試方法

                  A)  (expected=XXEception.class)

                B)  (timeout=xxx)

*.           @ Ignore: 被忽略的測試方法

*.           @Before: 每一個測試方法之前雲行。

*.           @After : 每一個測試方法之後運行。

*.           @BefreClass 所有測試開始之前運行。

*.           @AfterClass 所有測試結果之後運行。

------------------------------------------------------------------------------------------------

下面通過一個測試程式來解釋這些註解含義

package com.junit4.cc.test;

importstatic org.junit.Assert.*;
importstatic org.hamcrest.Matcher.*;

import org.junit.Test;
import com.junit4.cc.*;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.After;
import org.junit.Ignore;


publicclass TTest {

@BeforeClass //的所有方法運行之前運行。
publicstaticvoid beforeClass(){
System.out.println("------------beforeClass");
}

@AfterClass //在所有方法運行之後運行
publicstaticvoid afterClass(){
System.out.println("-------------afterClass");
}

@Before //每個測試方法運行之前運行
publicvoid before(){
System.out.println("=======before");
}

@After //每個測試方法運行之後運行
publicvoid after(){
System.out.println("=======after");
}

@Test
publicvoid testAdd() {
int z=new T().add(5,3);
assertEquals(8,z);
System.out.println("test Run through");
}

@Test ()
publicvoid testdivision(){
System.out.println("in Test Division");

}

@Ignore //表示這個方法是不被啟動並執行
@Test
(expected=java.lang.ArithmeticException.class,timeout=100) //timeout表示要求方法在100毫秒內運行完成,否則報錯
publicvoid testDivide(){
int z =new T().divide(8,2);
}



}

運行結果如下:

標記紅星(*)方法在每個方法開始和結尾都運行一次。

標記綠星(*)的方法只在所有方法的開始和結尾運行一次。

junit有多種註解,我們常用的也就上面幾種。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.