基於Junit3.8和Junit4.x的單元測試詳解,junit3.8junit4.x
轉載請註明出處:http://blog.csdn.net/lhy_ycu/article/details/45281449
前言
好久沒有寫來CSDN寫部落格了,前段時間一直在加班趕項目,所以部落格一直沒有更新;現在空閑時間比較多,所以後面會長期更新部落格。
今天來複習一下單元測試基於Junit工具的使用。Junit3.8與Junit4.x的使用還是有些區別的,所以分開來講,但不管怎樣,單元測試的目的並不是證明你是對的,而是為了證明你沒有錯誤,同時也為提高程式健壯性、可重用測試、降低代碼後期維護等提供了很好的支援和協助。
(一) 基於Junit3.8的執行個體說明
/** * 基本四則運算 -- 目標類 * * @author [*昨日重現*] lhy_ycu@163.com * @since version 1.0 * @datetime 2015年4月24日 上午10:35:13 */public class Calculator {private int add(int num1, int num2) {return num1 + num2;}public int subtract(int num1, int num2) {return num1 - num2;}public int multiply(int num1, int num2) {return num1 * num2;}public int divide(int num1, int num2) {if (num2 == 0) {throw new ArithmeticException("除數不能為0");}return num1 / num2;}}
基於Junit3.8的測試類別
/** * 基於Junit3.8 * * 測試原始碼中的目標類,測試類別必須繼承TestCase * * @author [*昨日重現*] lhy_ycu@163.com * @since version 1.0 * @datetime 2015年4月24日 上午10:43:22 */public class CalculatorTest extends TestCase {private Calculator cal = null;@Overrideprotected void setUp() throws Exception {// TODO Auto-generated method stubsuper.setUp();// 每個測試方法執行前,重新new一個對象,避免測試案例之間的依賴cal = new Calculator();System.out.println("在每個測試方法執行前執行--setUp...");}/** * 測試原始碼的私人方法 */public void testAdd() {System.out.println("測試方法testAdd...");// Assert.assertEquals(3, cal.add(1, 2));// blue bartry {// 1、getClass;2、Class.forName(); 3、.classClass<Calculator> calzz = Calculator.class;// Class<?> calzz = Class.forName("com.leo.junit.Calculator");// Calculator cal = calzz.newInstance();Method method = calzz.getDeclaredMethod("add", new Class[] {Integer.TYPE, Integer.TYPE });// 後兩個參數為:方法名、參數類型method.setAccessible(true);// 設定為可訪問私人的add方法// 後兩個參數為:目標類對象、實參對象;返回目標方法的結果Object obj = method.invoke(cal, new Object[] { 1, 2 });Assert.assertEquals(3, obj);} catch (Exception e) {// e.printStackTrace();Assert.fail();}}public void testSubstrub() {System.out.println("測試方法testSubstrub...");Assert.assertEquals(3, cal.subtract(1, 2));// red bar,failure 說明測試沒有通過(失敗)}public void testMultiply() {System.out.println("測試方法testMultiply...");Assert.assertEquals(2, cal.multiply(1, 2));// blue bar}public void testDivide() {System.out.println("測試方法testDivide...");Assert.assertEquals(2, cal.divide(1, 0));// red bar, error 說明測試程式本身出錯}@Overrideprotected void tearDown() throws Exception {// TODO Auto-generated method stubsuper.tearDown();// cal = null;// 在每個測試方法執行後主動銷毀對象System.out.println("在每個測試方法執行後執行--tearDown...\n");}// public static void main(String[] args) {// junit.textui.TestRunner.run(CalculatorTest.class);// 控制台列印錯誤記錄檔// }}
注意事項:
1)Junit的原則:keep the bar green to keep the code clean。2)測試類別與(原始碼)目標類的包名盡量要一致,最終它們都會被編譯到同一個目錄下面,這樣就不用匯入原始碼所在的包。
3) 測試類別的命名規則:測試類別類名 = 目標類類名前或後加Test; 注意要統一。
4) 測試類別必須繼承TestCase; 測試案例(方法/類)與測試案例之間一定是完全獨立的,不允許出現任何的依賴關係。同時也不能依賴測試方法的執行順序,也就是刪除或注釋掉某個測試方法後,其他的測試方法依然能夠執行。
5) 測試原始碼的私人方法可以採取兩種方式:1、修改目標方法的存取修飾詞(將private修改為public,一般不推薦);2、使用反射在測試類別中調用目標類的私人方法。
(二)基於Junit4.x的執行個體說明
/** * 基於Junit4.X --主要基於註解Annotation * * @author [*昨日重現*] lhy_ycu@163.com * @since version 1.0 * @datetime 2015年4月25日 上午12:06:52 */// @Ignore 將忽略掉該類的所有測試方法public class CalculatorTest2 {private Calculator cal = null;@BeforeClasspublic static void beforeClass() {System.out.println("=========在所有測試方法執行前執行--beforeClass=====\n");}/** * 在測試方法執行完前執行 */@Beforepublic void beforeMethod() {System.out.println("在每個測試方法執行前執行--beforeMethod...");cal = new Calculator();}// 若逾時1s,將報error錯誤@Test(timeout = 1000)// 若期待有異常拋出:expected = Exception.classpublic void testSubstrub() // throws Exception{System.out.println("測試方法testSubstrub被執行...");Assert.assertEquals(-1, cal.subtract(1, 2));// Assert.assertEquals(-1, cal.divide(1, 0));}@Test@Ignore("該testMultiply測試方法由於XX原因需要被忽略掉")public void testMultiply() {System.out.println("測試方法testMultiply被執行...");Assert.assertEquals(2, cal.multiply(1, 2));}/** * assertThat及Hamcrest的基本使用 */@Testpublic void testOther() {int result = cal.subtract(1, 2);// 關於字串String s1 = "leo";org.junit.Assert.assertThat(result, Matchers.is(-1));org.junit.Assert.assertThat(s1, Matchers.not("llleo"));// org.junit.Assert.assertThat(s1, Matchers.equalToIgnoringCase("LeO"));// org.junit.Assert.assertThat(s1,// Matchers.equalToIgnoringWhiteSpace(" Leo "));// org.junit.Assert.assertThat(s1, Matchers.containsString("leo"));// org.junit.Assert.assertThat(s1, Matchers.startsWith("le"));// org.junit.Assert.assertThat(s1, Matchers.endsWith("o"));// org.junit.Assert.assertThat(s1, Matchers.equalTo("leo"));// 關於基本類型double d1 = 3.1;// 在3.0±0.2之間org.junit.Assert.assertThat(d1, Matchers.closeTo(3.0, 0.2));// 大於3.0org.junit.Assert.assertThat(d1, Matchers.greaterThan(3.0));// 小於4.0org.junit.Assert.assertThat(d1, Matchers.lessThan(4.0));// 大於或等於3.0org.junit.Assert.assertThat(d1, Matchers.greaterThanOrEqualTo(3.0));// 小於或等於4.0org.junit.Assert.assertThat(d1, Matchers.lessThanOrEqualTo(4.0));// 關於集合Map<String, String> map = new HashMap<String, String>();map.put("k1", "zhangsan");map.put("k2", "lisi");// 是否含有該k1=zhangsan的索引值對org.junit.Assert.assertThat(map, Matchers.hasEntry("k1", "zhangsan"));// 是否含有鍵為k2的Itemorg.junit.Assert.assertThat(map, Matchers.hasKey("k2"));// 是否含有值為lisi的Itemorg.junit.Assert.assertThat(map, Matchers.hasValue("lisi"));}/** * 在測試方法執行完後執行 */@Afterpublic void afterMethod() {// cal = null;// 在每個測試方法執行後主動銷毀對象System.out.println("在每個測試方法執行後執行--afterMethod...\n");}@AfterClasspublic static void afterClass() {System.out.println("=========在所有測試方法執行後執行--afterClass=====");}}
注意事項:
1)在一個測試類別中,所有被@Test註解所修飾的public void方法都是測試案例,可以被JUnit所執行。
2) failure是指測試失敗,而error是指測試程式本身出錯。
結束語
明天開始續《Java學習系列》,包括反射、註解、內部類等等。