`

JUnit4 和JUnit3的区别

    博客分类:
  • Java
阅读更多

    为了说明JUnit4JUnit3 的区别,我们先看代码:
    Largest.java: 这是一个测试类

//测试类
public class Largest {
  public Largest() {
  }
   public static int largest(int[] list){//用于求该数组的最大值,为了测试方便,该方法为静态方法
     int index,max=Integer.MAX_VALUE;
     for(index=0;index<list.length-1;index++){
       if(list[index]>max){
         max=list[index];
       }
     }
     return max;
   }
}

    首先看JUnit3 的 测试用例:TestLargest.java :

import junit.framework.TestCase;

//这是用Junit3创建的,没有报错。
public class TestLarget extends TestCase {

 protected void setUp() throws Exception {
  super.setUp();
 }
 
 public void testSimple()
 {
  assertEquals (9, Largest.largest(new int[]{9,8,7}));
 }

 protected void tearDown() throws Exception {
  super.tearDown();
 }

}

   然后我们再看用JUnit4 的测试用例:TestLargest.java:

//注意下面的包org.junit.After,org.junit.Before
import org.junit.After;
import org.junit.Before;
//为了测试自己写的脚本,要引入包:
import org.junit.Test;
import org.junit.Assert;//assertEquals方法等都在Assert.中

//此种是自己New的一个Junit Test Case, 然后选择了自动添加setUp和tearDown方法。注意在两个方法的前面有两个标记:@Before和@After
public class TestLargest {

 @Before
 public void setUp() throws Exception {
 }

 @Test //此处必须加
 public void testSimple()
 {
  //assetEquals(9,Largest.largest(new int[]{9,8,7}));//为什么assetEquals()报错呢
  Assert.assertEquals( 9,Largest.largest(new int[]{9,8,7}));//避免上面的错误,要用此种形式
 }
 @After
 public void tearDown() throws Exception {
 }

}

    下面的这个是右键 Largest.java,New->JUnit Test Case,自动生成的测试框架(JUnit4),LargestTest.java:

import static org.junit.Assert.*;

import org.junit.Test;

//此种方法为自动生成的框架。然后填写代码即可。右键 Larget.java,New->Junit Test Case
public class LargestTest {

 @Test
 public void testLargest() {
  fail("Not yet implemented");
 }
}

    然后我们自己添加代码即可。
    有上面的代码对比,我们可以总结JUnit4和JUnit3的区别 主 要有两点:
    1. JUnit4 利用了 Java 5 的新特性 " 注释 " ,每个测试方法都不需要以 testXXX 的方式命名 , 行时不在用反射机制来查找并测试方法,取而带之是用 @Test 来标注每个测试方法,效率提升
    2. JUnit4中 测试类不必 继承 TestCase 了, 另外要注意JUnit4和JUnit3引入的包完全不同。
            PS: Eclipse 中要使用 Junit 的话,必须要添加 Junit library
    3.JUnit4和JUnit3在测试Suite时也有很大不同: 例如我们有两个测试类Product.javaShoppingCart.java ,还涉及到一个异常类ProductNotFoundException.java:

Product.java:

public class Product {
  private String title;
 private double price;

 public Product(String title, double price) {
     this.title = title;
     this.price = price;
 }

 public String getTitle() {
     return title;
 }

 public double getPrice() {
     return price;
 }

 public boolean equals(Object o) {
     if (o instanceof Product) {
         Product p = (Product)o;
         return p.getTitle().equals(title);
     }

     return false;
 }

}


ShoppingCart.java:

import java.util.*;

public class ShoppingCart
{
  private  ArrayList items;
 
  public ShoppingCart()
  {
    items=new ArrayList();
  }
   public double getbalance()
   {
     double balance=0.00;
     for(Iterator i=items.iterator();i.hasNext();)
     {
       Product item=(Product)i.next();
       balance+=item.getPrice();
     }
     return balance;
     }
  
    public void addItem(Product item) {
      items.add(item);
  }

  public void removeItem(Product item) throws ProductNotFoundException {
      if (!items.remove(item)) {
          throw new ProductNotFoundException();
      }
  }

  public int getItemCount() {
      return items.size();
  }

  public void empty() {
      items.clear();
  }
}


ProductNotFoundException.java:


public class ProductNotFoundException extends Exception {

    public ProductNotFoundException() {
        super();
    }
}
    下面是用JUnit4 写的测试类:
ProductTest.java:

import junit.framework.TestCase;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;


public class ProductTest extends TestCase//extends完全可以不写,只是为了把测试方法加入到suite中
{

 private Product p;
 public ProductTest() {
   }
 
 //这是为了AllTests类做的铺垫
 public ProductTest(String method)
 {
  super(method);
 }
 
 @Before
 public void setUp() throws Exception {
  p=new Product("a book",32.45);
 }

 @After
 public void tearDown() throws Exception {
 }
 
 @Test
 public void testGetTitle()
   {
     Assert. assertEquals("a book",p.getTitle());
   }
 
 @Test
 public void testSameRefrence()
   {
     //product q=new product("a sheet",12.56);
     Product q=p;
     Assert. assertSame("not equale object",p,q);
   }
 @Test
    public void  testEquals()
    {
      String q="Yest";
      Assert. assertEquals("should not equal to a string object",false,p.equals(q));
    }
 
 @Test
    public void testGetPrice()
    {
      Assert. assertEquals(32.45,p.getPrice(),0.01);
    }

}


ShoppingCartTest.java:

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;


public class ShoppingCartTest {

  private ShoppingCart cart;
   private Product book1;
  
   public ShoppingCartTest(){
   }
 @Before
 public void setUp() throws Exception {
  cart = new ShoppingCart();
      book1 = new Product("Pragmatic Unit Testing", 29.95);
      cart.addItem(book1);
 }

 @After
 public void tearDown() throws Exception {
 }
 
 @Test
 public void testEmpty() {
       cart.empty();
       Assert. assertEquals(0, cart.getItemCount());
   }

 @Test
   public void testAddItem() {

       Product book2 = new Product("Pragmatic Project Automation", 29.95);
       cart.addItem(book2);

       Assert. assertEquals(2, cart.getItemCount());

       double expectedBalance = book1.getPrice() + book2.getPrice();
       
       Assert. assertEquals(expectedBalance, cart.getbalance(), 0.0);
   }


   //抛出异常
 @Test
   public void testRemoveItem() throws ProductNotFoundException {

       cart.removeItem(book1);
       Assert. assertEquals(0, cart.getItemCount());
   }

 @Test
   public void testRemoveItemNotInCart() {//需要捕捉异常
       try {

           Product book3 = new Product("Pragmatic Unit Testingx", 29.95);
           cart.removeItem(book3);

           Assert. fail("Should raise a ProductNotFoundException");

       } catch(ProductNotFoundException expected) {
        Assert. assertTrue(true);
       }
   }
}
    下面是测试套件的类:TestSuite.java(JUnit4)

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

//通过下面的形式运行套件,必 须构造一个空类
@RunWith(Suite.class)
@Suite.SuiteClasses({ShoppingCartTest.class,ProductTest.class})

public class TestSuite {

}
    另外为了在Suite添加一个测试方法,我们可以采用下面的一个办法:AllTests.java:

import junit.framework.Test;
import junit.framework.TestSuite;

public class AllTests {

 public static Test suite() {
  TestSuite suite = new TestSuite("Test for default package");
  suite.addTest(new ProductTest("testGetTitle"));//注意此时ProductTest必须要继承TestCase
  return suite;
 }

}
    作为对比,我们再看一下JUnit3 写的测试类:
productTest.java:

import junit.framework.TestCase;

public class productTest extends TestCase {
   private product p;
   public productTest() {
   }
   public void setUp()
   {
      p=new product("a book",32.45);
   }
   public void tearDown()
   {
   }
   public void test GetTitle()
   {
     assertEquals ("a book",p.getTitle());
   }
   public void test SameRefrence()
   {
     //product q=new product("a sheet",12.56);
     product q=p;
     assertSame ("not equale object",p,q);
   }
    public void  test Equales()
    {
      String q="Yest";
      assertEquals ("should not equal to a string object",false,p.equals(q));
    }
 }


ShoppingCartTest .java:

import junit.framework.*;

public class ShoppingCartTest extends TestCase {
  private ShoppingCart cart;
  private product book1;
  public ShoppingCartTest(){

  }
  public ShoppingCartTest(String method){
    super(method);
  }
  /**
   * 建立测试 fixture.
   * 每个test函数运行之前都执行.
   */
  protected void setUp() {

      cart = new ShoppingCart();

      book1 = new product("Pragmatic Unit Testing", 29.95);

      cart.addItem(book1);
  }

  /**
   * 销毁fixture.
   * 每个测试函数执行之后都运行
   */
  protected void tearDown() {
      // release objects under test here, as necessary
  }


  public void test Empty() {

      cart.empty();

      assertEquals (0, cart.getItemCount());
  }


  public void test AddItem() {

      product book2 = new product("Pragmatic Project Automation", 29.95);
      cart.addItem(book2);

      assertEquals (2, cart.getItemCount());

      double expectedBalance = book1.getPrice() + book2.getPrice();
      assertEquals (expectedBalance, cart.getbalance(), 0.0);
  }


  public void test RemoveItem() throws productNotFoundException {

      cart.removeItem(book1);

      assertEquals (0, cart.getItemCount());
  }


  public void test RemoveItemNotInCart() {

      try {

          product book3 = new product("Pragmatic Unit Testingx", 29.95);
          cart.removeItem(book3);

          fail("Should raise a ProductNotFoundException");

      } catch(productNotFoundException expected) {
          assertTrue (true);
      }
  }
  public static Test suite(){
    TestSuite suite=new TestSuite();
    suite.addTest(new ShoppingCartTest("testRemoveItem"));
    suite.addTest(new ShoppingCartTest("testRemoveItemNotInCart"));
    return suite;
  }

}
    下面这个是测试Suite的测试类:TestClassComposite .java(JUnit3):

import junit.framework.*;

public class TestClassComposite {//be a base class,extendding from TestCase is of no necessary.
  public static Test suite() { //注意suite的大小写
    TestSuite suite = new TestSuite();
    suite.addTestSuite(productTest.class);
    suite.addTest(ShoppingCartTest.suite());
    return suite;
  }
}
    通过代码,我们可以清楚的看到JUnit4和 JUnit2在测试套件时的区别,JUnit4在测试套件时,必须构造一个空类,而且使用Annotation的形式,即
@RunWith(Suite.class)
@Suite.SuiteClasses({ShoppingCartTest.class,ProductTest.class}),而JUuni3则 是普通的直接用函数调用,添加Suite。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics