为了说明JUnit4和JUnit3的区别,我们先看代码:    Largest.java:这是一个测试类//测试类 
 1
 public class Largest
public class Largest  {
{
 2
 public Largest()
  public Largest()  {
{
 3 }
  }
 4
 public static int largest(int[] list)
   public static int largest(int[] list) {//用于求该数组的最大值,为了测试方便,该方法为静态方法
{//用于求该数组的最大值,为了测试方便,该方法为静态方法
 5 int index,max=Integer.MAX_VALUE;
     int index,max=Integer.MAX_VALUE;
 6
 for(index=0;index<list.length-1;index++)
     for(index=0;index<list.length-1;index++) {
{
 7
 if(list[index]>max)
       if(list[index]>max) {
{
 8 max=list[index];
         max=list[index];
 9 }
       }
10 }
     }
11 return max;
     return max;
12 }
   }
13 }
} 
    首先看JUnit3的测试用例:TestLargest.java:
    
 1 import junit.framework.TestCase;
import junit.framework.TestCase;
 2
 3 //这是用Junit3创建的,没有报错。
//这是用Junit3创建的,没有报错。
 4
 public class TestLarget extends TestCase
public class TestLarget extends TestCase  {
{
 5
 6
 protected void setUp() throws Exception
 protected void setUp() throws Exception  {
{
 7 super.setUp();
  super.setUp();
 8 }
 }
 9 
 
10 public void testSimple()
 public void testSimple()
11
 
  {
{
12
 assertEquals(9, Largest.largest(new int[]
  assertEquals(9, Largest.largest(new int[] {9,8,7}));
{9,8,7}));
13 }
 }
14
15
 protected void tearDown() throws Exception
 protected void tearDown() throws Exception  {
{
16 super.tearDown();
  super.tearDown();
17 }
 }
18
19 }
}
20
21
 
 
   然后我们再看用JUnit4的测试用例:TestLargest.java:
    
 1 //注意下面的包org.junit.After,org.junit.Before
//注意下面的包org.junit.After,org.junit.Before
 2 import org.junit.After;
import org.junit.After;
 3 import org.junit.Before;
import org.junit.Before;
 4 //为了测试自己写的脚本,要引入包:
//为了测试自己写的脚本,要引入包:
 5 import org.junit.Test;
import org.junit.Test;
 6 import org.junit.Assert;//assertEquals方法等都在Assert.中
import org.junit.Assert;//assertEquals方法等都在Assert.中
 7
 8 //此种是自己New的一个Junit Test Case, 然后选择了自动添加setUp和tearDown方法。注意在两个方法的前面有两个标记:@Before和@After
//此种是自己New的一个Junit Test Case, 然后选择了自动添加setUp和tearDown方法。注意在两个方法的前面有两个标记:@Before和@After
 9
 public class TestLargest
public class TestLargest  {
{
10
11 @Before
 @Before
12
 public void setUp() throws Exception
 public void setUp() throws Exception  {
{
13 }
 }
14
15 @Test //此处必须加
 @Test //此处必须加
16 public void testSimple()
 public void testSimple()
17
 
  {
{
18 //assetEquals(9,Largest.largest(new int[]{9,8,7}));//为什么assetEquals()报错呢
  //assetEquals(9,Largest.largest(new int[]{9,8,7}));//为什么assetEquals()报错呢
19
 Assert.assertEquals(9,Largest.largest(new int[]
  Assert.assertEquals(9,Largest.largest(new int[] {9,8,7}));//避免上面的错误,要用此种形式
{9,8,7}));//避免上面的错误,要用此种形式
20 }
 }
21 @After
 @After
22
 public void tearDown() throws Exception
 public void tearDown() throws Exception  {
{
23 }
 }
24
25 }
}
26
27
 
 
    下面的这个是右键Largest.java,New->JUnit Test Case,自动生成的测试框架(JUnit4),LargestTest.java: 
 1 import static org.junit.Assert.*;
import static org.junit.Assert.*;
 2
 3 import org.junit.Test;
import org.junit.Test;
 4
 5 //此种方法为自动生成的框架。然后填写代码即可。右键Larget.java,New->Junit Test Case
//此种方法为自动生成的框架。然后填写代码即可。右键Larget.java,New->Junit Test Case 
 6
 public class LargestTest
public class LargestTest  {
{
 7
 8 @Test
 @Test
 9
 public void testLargest()
 public void testLargest()  {
{
10 fail("Not yet implemented");
  fail("Not yet implemented");
11 }
 }
12 }
}
13
14
 
 
    然后我们自己添加代码即可。    有上面的代码对比,我们可以总结JUnit4和JUnit3的区别主要有两点:    1. JUnit4利用了 Java 5 的新特性"注释",每个测试方法都不需要以testXXX的方式命名,运行时不在用反射机制来查找并测试方法,取而带之是用@Test来标注每个测试方法,效率提升
    2. JUnit4中测试类不必继承TestCase了,另外要注意JUnit4和JUnit3引入的包完全不同。
    3.JUnit4和JUnit3在测试Suite时也有很大不同:例如我们有两个测试类Product.java,ShoppingCart.java,还涉及到一个异常类ProductNotFoundException.java:
Product.java:
    
 1
 public class Product
public class Product  {
{
 2 private String title;
  private String title;
 3 private double price;
 private double price;
 4
 5
 public Product(String title, double price)
 public Product(String title, double price)  {
{
 6 this.title = title;
     this.title = title;
 7 this.price = price;
     this.price = price;
 8 }
 }
 9
10
 public String getTitle()
 public String getTitle()  {
{
11 return title;
     return title;
12 }
 }
13
14
 public double getPrice()
 public double getPrice()  {
{
15 return price;
     return price;
16 }
 }
17
18
 public boolean equals(Object o)
 public boolean equals(Object o)  {
{
19
 if (o instanceof Product)
     if (o instanceof Product)  {
{
20 Product p = (Product)o;
         Product p = (Product)o;
21 return p.getTitle().equals(title);
         return p.getTitle().equals(title);
22 }
     }
23
24 return false;
     return false;
25 }
 }
26
27 }
}
28
29
 
ShoppingCart.java:
1 import java.util.*;
import java.util.*;
2
3 public class ShoppingCart
public class ShoppingCart
4

 {
{
5 private ArrayList items;
 private ArrayList items;
6 
 
7 public ShoppingCart()
 public ShoppingCart()
8
 
  {
{
9 items=new ArrayList();
 items=new ArrayList();
10 }
 }
11 public double getbalance()
 public double getbalance()
12
 
  {
{
13 double balance=0.00;
 double balance=0.00;
14 for(Iterator i=items.iterator();i.hasNext();)
 for(Iterator i=items.iterator();i.hasNext();)
15
 
  {
{
16 Product item=(Product)i.next();
 Product item=(Product)i.next();
17 balance+=item.getPrice();
 balance+=item.getPrice();
18 }
 }
19 return balance;
 return balance;
20 }
 }
21 
 
22
 public void addItem(Product item)
 public void addItem(Product item)  {
{
23 items.add(item);
 items.add(item);
24 }
 }
25
26
 public void removeItem(Product item) throws ProductNotFoundException
 public void removeItem(Product item) throws ProductNotFoundException  {
{
27
 if (!items.remove(item))
 if (!items.remove(item))  {
{
28 throw new ProductNotFoundException();
 throw new ProductNotFoundException();
29 }
 }
30 }
 }
31
32
 public int getItemCount()
 public int getItemCount()  {
{
33 return items.size();
 return items.size();
34 }
 }
35
36
 public void empty()
 public void empty()  {
{
37 items.clear();
 items.clear();
38 }
 }
39 }
}
40
41
 
ProductNotFoundException.java:
1
 public class ProductNotFoundException extends Exception
public class ProductNotFoundException extends Exception  {
{
2
 public ProductNotFoundException()
    public ProductNotFoundException()  {
{
3 super();
        super();
4 }
    }
5 }
}
6
 
    下面是用JUnit4写的测试类:
ProductTest.java:
 1 import junit.framework.TestCase;
import junit.framework.TestCase;
 2
 3 import org.junit.After;
import org.junit.After;
 4 import org.junit.Before;
import org.junit.Before;
 5 import org.junit.Test;
import org.junit.Test;
 6 import org.junit.Assert;
import org.junit.Assert;
 7
 8
 9 public class ProductTest extends TestCase//extends完全可以不写,只是为了把测试方法加入到suite中
public class ProductTest extends TestCase//extends完全可以不写,只是为了把测试方法加入到suite中
10

 {
{
11
12 private Product p;
 private Product p;
13
 public ProductTest()
 public ProductTest()  {
{
14 }
   }
15 
 
16 //这是为了AllTests类做的铺垫
 //这是为了AllTests类做的铺垫
17 public ProductTest(String method)
 public ProductTest(String method)
18
 
  {
{
19 super(method);
  super(method);
20 }
 }
21 
 
22 @Before
 @Before
23
 public void setUp() throws Exception
 public void setUp() throws Exception  {
{
24 p=new Product("a book",32.45);
  p=new Product("a book",32.45);
25 }
 }
26
27 @After
 @After
28
 public void tearDown() throws Exception
 public void tearDown() throws Exception  {
{
29 }
 }
30 
 
31 @Test
 @Test
32 public void testGetTitle()
 public void testGetTitle()
33
 
    {
{
34 Assert.assertEquals("a book",p.getTitle());
     Assert.assertEquals("a book",p.getTitle());
35 }
   }
36 
 
37 @Test
 @Test
38 public void testSameRefrence()
 public void testSameRefrence()
39
 
    {
{
40 //product q=new product("a sheet",12.56);
     //product q=new product("a sheet",12.56);
41 Product q=p;
     Product q=p;
42 Assert.assertSame("not equale object",p,q);
     Assert.assertSame("not equale object",p,q);
43 }
   }
44 @Test
 @Test
45 public void  testEquals()
    public void  testEquals()
46
 
     {
{
47 String q="Yest";
      String q="Yest";
48 Assert.assertEquals("should not equal to a string object",false,p.equals(q));
      Assert.assertEquals("should not equal to a string object",false,p.equals(q));
49 }
    }
50 
 
51 @Test
 @Test
52 public void testGetPrice()
    public void testGetPrice()
53
 
     {
{
54 Assert.assertEquals(32.45,p.getPrice(),0.01);
      Assert.assertEquals(32.45,p.getPrice(),0.01);
55 }
    }
56
57 }
}
58
59
 
 
 
ShoppingCartTest.java:
 1 import org.junit.After;
import org.junit.After;
 2 import org.junit.Assert;
import org.junit.Assert;
 3 import org.junit.Before;
import org.junit.Before;
 4 import org.junit.Test;
import org.junit.Test;
 5
 6
 7
 public class ShoppingCartTest
public class ShoppingCartTest  {
{
 8
 9 private ShoppingCart cart;
  private ShoppingCart cart;
10 private Product book1;
   private Product book1;
11 
   
12
 public ShoppingCartTest()
   public ShoppingCartTest() {
{
13 }
   }
14 @Before
 @Before
15
 public void setUp() throws Exception
 public void setUp() throws Exception  {
{
16 cart = new ShoppingCart();
  cart = new ShoppingCart();
17 book1 = new Product("Pragmatic Unit Testing", 29.95);
      book1 = new Product("Pragmatic Unit Testing", 29.95);
18 cart.addItem(book1);
      cart.addItem(book1);
19 }
 }
20
21 @After
 @After
22
 public void tearDown() throws Exception
 public void tearDown() throws Exception  {
{
23 }
 }
24 
 
25 @Test
 @Test
26
 public void testEmpty()
 public void testEmpty()  {
{
27 cart.empty();
       cart.empty();
28 Assert.assertEquals(0, cart.getItemCount());
       Assert.assertEquals(0, cart.getItemCount());
29 }
   }
30
31 @Test
 @Test
32
 public void testAddItem()
   public void testAddItem()  {
{
33
34 Product book2 = new Product("Pragmatic Project Automation", 29.95);
       Product book2 = new Product("Pragmatic Project Automation", 29.95);
35 cart.addItem(book2);
       cart.addItem(book2);
36
37 Assert.assertEquals(2, cart.getItemCount());
       Assert.assertEquals(2, cart.getItemCount());
38
39 double expectedBalance = book1.getPrice() + book2.getPrice();
       double expectedBalance = book1.getPrice() + book2.getPrice();
40 
       
41 Assert.assertEquals(expectedBalance, cart.getbalance(), 0.0);
       Assert.assertEquals(expectedBalance, cart.getbalance(), 0.0);
42 }
   }
43
44
45 //抛出异常
   //抛出异常
46 @Test
 @Test
47
 public void testRemoveItem() throws ProductNotFoundException
   public void testRemoveItem() throws ProductNotFoundException  {
{
48
49 cart.removeItem(book1);
       cart.removeItem(book1);
50 Assert.assertEquals(0, cart.getItemCount());
       Assert.assertEquals(0, cart.getItemCount());
51 }
   }
52
53 @Test
 @Test
54
 public void testRemoveItemNotInCart()
   public void testRemoveItemNotInCart()  {//需要捕捉异常
{//需要捕捉异常
55
 try
       try  {
{
56
57 Product book3 = new Product("Pragmatic Unit Testingx", 29.95);
           Product book3 = new Product("Pragmatic Unit Testingx", 29.95);
58 cart.removeItem(book3);
           cart.removeItem(book3);
59
60 Assert.fail("Should raise a ProductNotFoundException");
           Assert.fail("Should raise a ProductNotFoundException");
61
62
 } catch(ProductNotFoundException expected)
       } catch(ProductNotFoundException expected)  {
{
63 Assert.assertTrue(true);
        Assert.assertTrue(true);
64 }
       }
65 }
   }
66 }
}
67
68
 
 
    下面是测试套件的类:TestSuite.java(JUnit4)
 1 import org.junit.runner.RunWith;
import org.junit.runner.RunWith;
 2 import org.junit.runners.Suite;
import org.junit.runners.Suite;
 3
 4 //通过下面的形式运行套件,必须构造一个空类
//通过下面的形式运行套件,必须构造一个空类
 5 @RunWith(Suite.class)
@RunWith(Suite.class)
 6
 @Suite.SuiteClasses(
@Suite.SuiteClasses( {ShoppingCartTest.class,ProductTest.class})
{ShoppingCartTest.class,ProductTest.class})
 7
 8
 public class TestSuite
public class TestSuite  {
{
 9
10 }
}
11
12
 
 
    另外为了在Suite添加一个测试方法,我们可以采用下面的一个办法:AllTests.java:
 1 import junit.framework.Test;
import junit.framework.Test;
 2 import junit.framework.TestSuite;
import junit.framework.TestSuite;
 3
 4
 public class AllTests
public class AllTests  {
{
 5
 6
 public static Test suite()
 public static Test suite()  {
{
 7 TestSuite suite = new TestSuite("Test for default package");
  TestSuite suite = new TestSuite("Test for default package");
 8 suite.addTest(new ProductTest("testGetTitle"));//注意此时ProductTest必须要继承TestCase
  suite.addTest(new ProductTest("testGetTitle"));//注意此时ProductTest必须要继承TestCase
 9 return suite;
  return suite;
10 }
 }
11
12 }
}
13
14
 
 
    作为对比,我们再看一下JUnit3写的测试类:
 1 productTest.java:
productTest.java:
 2
 3 import junit.framework.TestCase;
import junit.framework.TestCase;
 4
 5
 public class productTest extends TestCase
public class productTest extends TestCase  {
{
 6 private product p;
   private product p;
 7
 public productTest()
   public productTest()  {
{
 8 }
   }
 9 public void setUp()
   public void setUp()
10
 
    {
{
11 p=new product("a book",32.45);
      p=new product("a book",32.45);
12 }
   }
13 public void tearDown()
   public void tearDown()
14
 
    {
{
15 }
   }
16 public void testGetTitle()
   public void testGetTitle()
17
 
    {
{
18 assertEquals("a book",p.getTitle());
     assertEquals("a book",p.getTitle());
19 }
   }
20 public void testSameRefrence()
   public void testSameRefrence()
21
 
    {
{
22 //product q=new product("a sheet",12.56);
     //product q=new product("a sheet",12.56);
23 product q=p;
     product q=p;
24 assertSame("not equale object",p,q);
     assertSame("not equale object",p,q);
25 }
   }
26 public void  testEquales()
    public void  testEquales()
27
 
     {
{
28 String q="Yest";
      String q="Yest";
29 assertEquals("should not equal to a string object",false,p.equals(q));
      assertEquals("should not equal to a string object",false,p.equals(q));
30 }
    }
31 }
 }
32
 
ShoppingCartTest.java:
 1 import junit.framework.*;
import junit.framework.*;
 2
 3
 public class ShoppingCartTest extends TestCase
public class ShoppingCartTest extends TestCase  {
{
 4 private ShoppingCart cart;
  private ShoppingCart cart;
 5 private product book1;
  private product book1;
 6
 public ShoppingCartTest()
  public ShoppingCartTest() {
{
 7
 8 }
  }
 9
 public ShoppingCartTest(String method)
  public ShoppingCartTest(String method) {
{
10 super(method);
    super(method);
11 }
  }
12
 /** *//**
  /** *//**
13 * 建立测试 fixture.
   * 建立测试 fixture.
14 * 每个test函数运行之前都执行.
   * 每个test函数运行之前都执行.
15 */
   */
16
 protected void setUp()
  protected void setUp()  {
{
17
18 cart = new ShoppingCart();
      cart = new ShoppingCart();
19
20 book1 = new product("Pragmatic Unit Testing", 29.95);
      book1 = new product("Pragmatic Unit Testing", 29.95);
21
22 cart.addItem(book1);
      cart.addItem(book1);
23 }
  }
24
25
 /** *//**
  /** *//**
26 * 销毁fixture.
   * 销毁fixture.
27 * 每个测试函数执行之后都运行
   * 每个测试函数执行之后都运行
28 */
   */
29
 protected void tearDown()
  protected void tearDown()  {
{
30 // release objects under test here, as necessary
      // release objects under test here, as necessary
31 }
  }
32
33
34
 public void testEmpty()
  public void testEmpty()  {
{
35
36 cart.empty();
      cart.empty();
37
38 assertEquals(0, cart.getItemCount());
      assertEquals(0, cart.getItemCount());
39 }
  }
40
41
42
 public void testAddItem()
  public void testAddItem()  {
{
43
44 product book2 = new product("Pragmatic Project Automation", 29.95);
      product book2 = new product("Pragmatic Project Automation", 29.95);
45 cart.addItem(book2);
      cart.addItem(book2);
46
47 assertEquals(2, cart.getItemCount());
      assertEquals(2, cart.getItemCount());
48
49 double expectedBalance = book1.getPrice() + book2.getPrice();
      double expectedBalance = book1.getPrice() + book2.getPrice();
50 assertEquals(expectedBalance, cart.getbalance(), 0.0);
      assertEquals(expectedBalance, cart.getbalance(), 0.0);
51 }
  }
52
53
54
 public void testRemoveItem() throws productNotFoundException
  public void testRemoveItem() throws productNotFoundException  {
{
55
56 cart.removeItem(book1);
      cart.removeItem(book1);
57
58 assertEquals(0, cart.getItemCount());
      assertEquals(0, cart.getItemCount());
59 }
  }
60
61
62
 public void testRemoveItemNotInCart()
  public void testRemoveItemNotInCart()  {
{
63
64
 try
      try  {
{
65
66 product book3 = new product("Pragmatic Unit Testingx", 29.95);
          product book3 = new product("Pragmatic Unit Testingx", 29.95);
67 cart.removeItem(book3);
          cart.removeItem(book3);
68
69 fail("Should raise a ProductNotFoundException");
          fail("Should raise a ProductNotFoundException");
70
71
 } catch(productNotFoundException expected)
      } catch(productNotFoundException expected)  {
{
72 assertTrue(true);
          assertTrue(true);
73 }
      }
74 }
  }
75
 public static Test suite()
  public static Test suite() {
{
76 TestSuite suite=new TestSuite();
    TestSuite suite=new TestSuite();
77 suite.addTest(new ShoppingCartTest("testRemoveItem"));
    suite.addTest(new ShoppingCartTest("testRemoveItem"));
78 suite.addTest(new ShoppingCartTest("testRemoveItemNotInCart"));
    suite.addTest(new ShoppingCartTest("testRemoveItemNotInCart"));
79 return suite;
    return suite;
80 }
  }
81 }
}
82
83
 
 
 
    下面这个是测试Suite的测试类:TestClassComposite.java(JUnit3):
 1 import junit.framework.*;
import junit.framework.*;
 2
 3
 public class TestClassComposite
public class TestClassComposite  {//be a base class,extendding from TestCase is of no necessary.
{//be a base class,extendding from TestCase is of no necessary.
 4
 public static Test suite()
  public static Test suite()  { //注意suite的大小写
{ //注意suite的大小写
 5 TestSuite suite = new TestSuite();
    TestSuite suite = new TestSuite();
 6 suite.addTestSuite(productTest.class);
    suite.addTestSuite(productTest.class);
 7 suite.addTest(ShoppingCartTest.suite());
    suite.addTest(ShoppingCartTest.suite());
 8 return suite;
    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 阅读(2272) 
评论(0)  编辑  收藏  所属分类: 
Program