标签:
1 package can.test;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import junit.framework.TestCase;
6
7 public class SampleTest extends TestCase {
8
9 protected void setUp() {
10 /* 开始test前的准备操作:初始化,获取数据连接... */
11
12 }
13
14 protected void tearDown() {
15 /* 完成test后的清理工作:关闭文件, 关闭数据连接... */
16
17 }
18
19 public void testEmpty() {
20 /* test case 1*/
21 Collection collection = new ArrarList();
22 assertTrue(collection.isEmpty());
23 }
24
25 public void testCase2() {
26 /* test case 2*/
27 ArrayList emptyList = new ArrayList();
28 try {
29 Object o = emptyList.get(0);
30 fail("Should raise an IndexOutOfBoundsException");
31 } catch (IndexOutOfBoundsException expected) {
32 assertTrue(true);
33 }
34 }
35 }
1. 当需要进行test前后操作,则对setUp(), tearDown()这两个方法进行重写。
import junit.framework.Test;
import junit.framework.TestSuite;
public static Test suite() {
/* 添加SampleTest类到TestSuite*/
return new TestSuite(SampleTest.class);
}
public static void main(String args[]) {
/* 指定文本界面*/
junit.textui.TestRunner.run(suite());
}
或者
public static void main(String args[]) {
junit.textui.TestRunner.run(SampleTest.class);
}
1 package can.junit;
2
3 import junit.framework.Test;
4 import junit.framework.TestSuite;
5
6 public class SampleTestSuite {
7
8 public static Test suite() {
9 TestSuite suite = new TestSuite("Sample Tests");
10
11 /* 逐一添加testCase类 */
12 suite.addTestSuite(SampleTest.class);
13
14 /* 逐一添加test suite(注意,这是递归调用的) */
15 suite.addTest(AnotherTestSuite.suite());
16
17 return suite;
18 }
19
20 public static void main(String args[]) {
21 junit.textui.TestRunner.run(suite());
22 }
23 }
刚才说了,每进行一个test case,setUp()和tearDown()都会调用。而有的时候,在setUp()中相当耗费资源,我们想进行所有的test case仅调用一次setUp()和tearDown(),这样需要把TestSuite包装到TestSetup类中:
1 import junit.framework.*;
2 import junit.extensions.TestSetup;
3
4 public class AllTestsOneTimeSetup {
5
6 public static Test suite() {
7
8 TestSuite suite = new TestSuite();
9 suite.addTest(SomeTest.suite());
10 suite.addTest(AnotherTest.suite());
11
12 TestSetup wrapper = new TestSetup(suite) {
13 protected void setUp() {
14 oneTimeSetUp();
15 }
16
17 protected void tearDown() {
18 oneTimeTearDown();
19 }
20 };
21 return wrapper;
22 }
23
24 public static void oneTimeSetUp() {
25 // one-time initialization code
26 }
27
28 public static void oneTimeTearDown() {
29 // one-time cleanup code
30 }
31 }
标签:
原文地址:http://www.cnblogs.com/Zhao-Yue/p/5900450.html