I want to fly higher
          programming Explorer
          posts - 114,comments - 263,trackbacks - 0
              為了說明JUnit4JUnit3的區別,我們先看代碼:
              Largest.java:這是一個測試類
          //測試類
           1public class Largest {
           2  public Largest() {
           3  }

           4   public static int largest(int[] list){//用于求該數組的最大值,為了測試方便,該方法為靜態方法
           5     int index,max=Integer.MAX_VALUE;
           6     for(index=0;index<list.length-1;index++){
           7       if(list[index]>max){
           8         max=list[index];
           9       }

          10     }

          11     return max;
          12   }

          13}

              首先看JUnit3的測試用例:TestLargest.java:

              

           1import junit.framework.TestCase;
           2
           3//這是用Junit3創建的,沒有報錯。
           4public class TestLarget extends TestCase {
           5
           6 protected void setUp() throws Exception {
           7  super.setUp();
           8 }

           9 
          10 public void testSimple()
          11 {
          12  assertEquals(9, Largest.largest(new int[]{9,8,7}));
          13 }

          14
          15 protected void tearDown() throws Exception {
          16  super.tearDown();
          17 }

          18
          19}

          20
          21

           

             然后我們再看用JUnit4的測試用例:TestLargest.java:

              

           1//注意下面的包org.junit.After,org.junit.Before
           2import org.junit.After;
           3import org.junit.Before;
           4//為了測試自己寫的腳本,要引入包:
           5import org.junit.Test;
           6import org.junit.Assert;//assertEquals方法等都在Assert.中
           7
           8//此種是自己New的一個Junit Test Case, 然后選擇了自動添加setUp和tearDown方法。注意在兩個方法的前面有兩個標記:@Before和@After
           9public class TestLargest {
          10
          11 @Before
          12 public void setUp() throws Exception {
          13 }

          14
          15 @Test //此處必須加
          16 public void testSimple()
          17 {
          18  //assetEquals(9,Largest.largest(new int[]{9,8,7}));//為什么assetEquals()報錯呢
          19  Assert.assertEquals(9,Largest.largest(new int[]{9,8,7}));//避免上面的錯誤,要用此種形式
          20 }

          21 @After
          22 public void tearDown() throws Exception {
          23 }

          24
          25}

          26
          27

           

              下面的這個是右鍵Largest.java,New->JUnit Test Case,自動生成的測試框架(JUnit4),LargestTest.java:
           1import static org.junit.Assert.*;
           2
           3import org.junit.Test;
           4
           5//此種方法為自動生成的框架。然后填寫代碼即可。右鍵Larget.java,New->Junit Test Case 
           6public class LargestTest {
           7
           8 @Test
           9 public void testLargest() {
          10  fail("Not yet implemented");
          11 }

          12}

          13
          14

           

              然后我們自己添加代碼即可。
              有上面的代碼對比,我們可以總結JUnit4和JUnit3的區別主要有兩點:
              1. JUnit4利用了 Java 5 的新特性"注釋",每個測試方法都不需要以testXXX的方式命名,行時不在用反射機制來查找并測試方法,取而帶之是用@Test來標注每個測試方法,效率提升
              2. JUnit4中測試類不必繼承TestCase了,另外要注意JUnit4和JUnit3引入的包完全不同。
                      PS:Eclipse中要使用Junit的話,必須要添加Junitlibrary。
              3.JUnit4和JUnit3在測試Suite時也有很大不同:例如我們有兩個測試類Product.java,ShoppingCart.java,還涉及到一個異常類ProductNotFoundException.java:
          Product.java:
              
           1public class Product {
           2  private String title;
           3 private double price;
           4
           5 public Product(String title, double price) {
           6     this.title = title;
           7     this.price = price;
           8 }

           9
          10 public String getTitle() {
          11     return title;
          12 }

          13
          14 public double getPrice() {
          15     return price;
          16 }

          17
          18 public boolean equals(Object o) {
          19     if (o instanceof Product) {
          20         Product p = (Product)o;
          21         return p.getTitle().equals(title);
          22     }

          23
          24     return false;
          25 }

          26
          27}

          28
          29

          ShoppingCart.java:
          1import java.util.*;
          2
          3public class ShoppingCart
          4{
          5 private ArrayList items;
          6
          7 public ShoppingCart()
          8 {
          9 items=new ArrayList();
          10 }

          11 public double getbalance()
          12 {
          13 double balance=0.00;
          14 for(Iterator i=items.iterator();i.hasNext();)
          15 {
          16 Product item=(Product)i.next();
          17 balance+=item.getPrice();
          18 }

          19 return balance;
          20 }

          21
          22 public void addItem(Product item) {
          23 items.add(item);
          24 }

          25
          26 public void removeItem(Product item) throws ProductNotFoundException {
          27 if (!items.remove(item)) {
          28 throw new ProductNotFoundException();
          29 }

          30 }

          31
          32 public int getItemCount() {
          33 return items.size();
          34 }

          35
          36 public void empty() {
          37 items.clear();
          38 }

          39}

          40
          41

          ProductNotFoundException.java:

          1public class ProductNotFoundException extends Exception {
          2    public ProductNotFoundException() {
          3        super();
          4    }

          5}

          6


              下面是用JUnit4寫的測試類:
          ProductTest.java:

           1import junit.framework.TestCase;
           2
           3import org.junit.After;
           4import org.junit.Before;
           5import org.junit.Test;
           6import org.junit.Assert;
           7
           8
           9public class ProductTest extends TestCase//extends完全可以不寫,只是為了把測試方法加入到suite中
          10{
          11
          12 private Product p;
          13 public ProductTest() {
          14   }

          15 
          16 //這是為了AllTests類做的鋪墊
          17 public ProductTest(String method)
          18 {
          19  super(method);
          20 }

          21 
          22 @Before
          23 public void setUp() throws Exception {
          24  p=new Product("a book",32.45);
          25 }

          26
          27 @After
          28 public void tearDown() throws Exception {
          29 }

          30 
          31 @Test
          32 public void testGetTitle()
          33   {
          34     Assert.assertEquals("a book",p.getTitle());
          35   }

          36 
          37 @Test
          38 public void testSameRefrence()
          39   {
          40     //product q=new product("a sheet",12.56);
          41     Product q=p;
          42     Assert.assertSame("not equale object",p,q);
          43   }

          44 @Test
          45    public void  testEquals()
          46    {
          47      String q="Yest";
          48      Assert.assertEquals("should not equal to a string object",false,p.equals(q));
          49    }

          50 
          51 @Test
          52    public void testGetPrice()
          53    {
          54      Assert.assertEquals(32.45,p.getPrice(),0.01);
          55    }

          56
          57}

          58
          59

           

           


          ShoppingCartTest.java:

           1import org.junit.After;
           2import org.junit.Assert;
           3import org.junit.Before;
           4import org.junit.Test;
           5
           6
           7public class ShoppingCartTest {
           8
           9  private ShoppingCart cart;
          10   private Product book1;
          11   
          12   public ShoppingCartTest(){
          13   }

          14 @Before
          15 public void setUp() throws Exception {
          16  cart = new ShoppingCart();
          17      book1 = new Product("Pragmatic Unit Testing"29.95);
          18      cart.addItem(book1);
          19 }

          20
          21 @After
          22 public void tearDown() throws Exception {
          23 }

          24 
          25 @Test
          26 public void testEmpty() {
          27       cart.empty();
          28       Assert.assertEquals(0, cart.getItemCount());
          29   }

          30
          31 @Test
          32   public void testAddItem() {
          33
          34       Product book2 = new Product("Pragmatic Project Automation"29.95);
          35       cart.addItem(book2);
          36
          37       Assert.assertEquals(2, cart.getItemCount());
          38
          39       double expectedBalance = book1.getPrice() + book2.getPrice();
          40       
          41       Assert.assertEquals(expectedBalance, cart.getbalance(), 0.0);
          42   }

          43
          44
          45   //拋出異常
          46 @Test
          47   public void testRemoveItem() throws ProductNotFoundException {
          48
          49       cart.removeItem(book1);
          50       Assert.assertEquals(0, cart.getItemCount());
          51   }

          52
          53 @Test
          54   public void testRemoveItemNotInCart() {//需要捕捉異常
          55       try {
          56
          57           Product book3 = new Product("Pragmatic Unit Testingx"29.95);
          58           cart.removeItem(book3);
          59
          60           Assert.fail("Should raise a ProductNotFoundException");
          61
          62       }
           catch(ProductNotFoundException expected) {
          63        Assert.assertTrue(true);
          64       }

          65   }

          66}

          67
          68

           

              下面是測試套件的類:TestSuite.java(JUnit4)

           1import org.junit.runner.RunWith;
           2import org.junit.runners.Suite;
           3
           4//通過下面的形式運行套件,必須構造一個空類
           5@RunWith(Suite.class)
           6@Suite.SuiteClasses({ShoppingCartTest.class,ProductTest.class})
           7
           8public class TestSuite {
           9
          10}

          11
          12

           

              另外為了在Suite添加一個測試方法,我們可以采用下面的一個辦法:AllTests.java:

           1import junit.framework.Test;
           2import junit.framework.TestSuite;
           3
           4public class AllTests {
           5
           6 public static Test suite() {
           7  TestSuite suite = new TestSuite("Test for default package");
           8  suite.addTest(new ProductTest("testGetTitle"));//注意此時ProductTest必須要繼承TestCase
           9  return suite;
          10 }

          11
          12}

          13
          14

           

              作為對比,我們再看一下JUnit3寫的測試類:

           1productTest.java:
           2
           3import junit.framework.TestCase;
           4
           5public class productTest extends TestCase {
           6   private product p;
           7   public productTest() {
           8   }

           9   public void setUp()
          10   {
          11      p=new product("a book",32.45);
          12   }

          13   public void tearDown()
          14   {
          15   }

          16   public void testGetTitle()
          17   {
          18     assertEquals("a book",p.getTitle());
          19   }

          20   public void testSameRefrence()
          21   {
          22     //product q=new product("a sheet",12.56);
          23     product q=p;
          24     assertSame("not equale object",p,q);
          25   }

          26    public void  testEquales()
          27    {
          28      String q="Yest";
          29      assertEquals("should not equal to a string object",false,p.equals(q));
          30    }

          31 }

          32


          ShoppingCartTest.java:

           1import junit.framework.*;
           2
           3public class ShoppingCartTest extends TestCase {
           4  private ShoppingCart cart;
           5  private product book1;
           6  public ShoppingCartTest(){
           7
           8  }

           9  public ShoppingCartTest(String method){
          10    super(method);
          11  }

          12  /**
          13   * 建立測試 fixture.
          14   * 每個test函數運行之前都執行.
          15   */

          16  protected void setUp() {
          17
          18      cart = new ShoppingCart();
          19
          20      book1 = new product("Pragmatic Unit Testing"29.95);
          21
          22      cart.addItem(book1);
          23  }

          24
          25  /**
          26   * 銷毀fixture.
          27   * 每個測試函數執行之后都運行
          28   */

          29  protected void tearDown() {
          30      // release objects under test here, as necessary
          31  }

          32
          33
          34  public void testEmpty() {
          35
          36      cart.empty();
          37
          38      assertEquals(0, cart.getItemCount());
          39  }

          40
          41
          42  public void testAddItem() {
          43
          44      product book2 = new product("Pragmatic Project Automation"29.95);
          45      cart.addItem(book2);
          46
          47      assertEquals(2, cart.getItemCount());
          48
          49      double expectedBalance = book1.getPrice() + book2.getPrice();
          50      assertEquals(expectedBalance, cart.getbalance(), 0.0);
          51  }

          52
          53
          54  public void testRemoveItem() throws productNotFoundException {
          55
          56      cart.removeItem(book1);
          57
          58      assertEquals(0, cart.getItemCount());
          59  }

          60
          61
          62  public void testRemoveItemNotInCart() {
          63
          64      try {
          65
          66          product book3 = new product("Pragmatic Unit Testingx"29.95);
          67          cart.removeItem(book3);
          68
          69          fail("Should raise a ProductNotFoundException");
          70
          71      }
           catch(productNotFoundException expected) {
          72          assertTrue(true);
          73      }

          74  }

          75  public static Test suite(){
          76    TestSuite suite=new TestSuite();
          77    suite.addTest(new ShoppingCartTest("testRemoveItem"));
          78    suite.addTest(new ShoppingCartTest("testRemoveItemNotInCart"));
          79    return suite;
          80  }

          81}

          82
          83

           

           

              下面這個是測試Suite的測試類:TestClassComposite.java(JUnit3):

           1import junit.framework.*;
           2
           3public class TestClassComposite {//be a base class,extendding from TestCase is of no necessary.
           4  public static Test suite() //注意suite的大小寫
           5    TestSuite suite = new TestSuite();
           6    suite.addTestSuite(productTest.class);
           7    suite.addTest(ShoppingCartTest.suite());
           8    return suite;
           9  }

          10}

          11


              通過代碼,我們可以清楚的看到JUnit4和JUnit2在測試套件時的區別,JUnit4在測試套件時,必須構造一個空類,而且使用Annotation的形式,即
          @RunWith(Suite.class)
          @Suite.SuiteClasses({ShoppingCartTest.class,ProductTest.class}),而JUuni3則是普通的直接用函數調用,添加Suite。

           

          posted on 2010-07-15 19:53 landon 閱讀(2263) 評論(0)  編輯  收藏 所屬分類: Program
          主站蜘蛛池模板: 天镇县| 马关县| 淄博市| 平泉县| 隆德县| 开封县| 额尔古纳市| 大石桥市| 蒲城县| 郑州市| 都匀市| 兴安盟| 南昌县| 德州市| 习水县| 平武县| 凉山| 富川| 山东| 南木林县| 平凉市| 新河县| 渭源县| 峨眉山市| 蓬莱市| 江城| 庆阳市| 罗源县| 剑川县| 铜陵市| 施秉县| 阜阳市| 礼泉县| 河北区| 绥宁县| 中超| 博野县| 九江县| 凤阳县| 公安县| 株洲市|