我们先看一下在JUnit 3中我们是怎样写一个单元测试的。比如下面一个类:
public class AddOperation { public int add(int x,int y){ return x+y; } }
我们要测试add这个方法,我们写单元测试得这么写:
import junit.framework.TestCase; import static org.junit.Assert.*; public class AddOperationTest extends TestCase{ public void setUp() throws Exception { } public void tearDown() throws Exception { } public void testAdd() { System.out.println(\"add\"); int x = 0; int y = 0; AddOperation instance = new AddOperation(); int expResult = 0; int result = instance.add(x, y); assertEquals(expResult, result); } }
import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class AddOperationTest extends TestCase{ public AddOperationTest() { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void add() { System.out.println(\"add\"); int x = 0; int y = 0; AddOperation instance = new AddOperation(); int expResult = 0; int result = instance.add(x, y); assertEquals(expResult, result); } }我们可以看到,采用Annotation的JUnit已经不会霸道的要求你必须继承自TestCase了,而且测试方法也不必以test开头了,只要以@Test元数据来描述即可。
来源:http://www.cnblogs.com/eggbucket/archive/2012/02/02/2335697.html
原文地址:http://blog.csdn.net/fanfan159357/article/details/43153635