Junit测试代码基本骨架

上一篇 / 下一篇  2009-09-03 15:53:24 / 个人分类:单元测试

51Testing软件测试网&{*W,KNfu q*C!kkk.CS+V

Junit写出来测试代码的基本骨架的样式大概就是下面的:

])Q{8A ]1m `0

!eo'F/v;`!O8SW0基本顺序就是

5C1}m9iH4~"F%m051Testing软件测试网7^ P]'bSusW;X-k

(1) import junit.framework.* 下面所有的类51Testing软件测试网,EL __/HL6R%\,i

51Testing软件测试网8ji PSU_C

(2) extends 用自己的测试类继承TestCase

(J.L#L9l bWeo0

k%V R GU-a3_x3J`0(3) 初始化和释放资源的方法 setUp()和tearDown()51Testing软件测试网9iT:j:BZ%i&\5Y*]

C CPB8?Q*f0(4) 写一个构造函数用super 调用 父类构造函数51Testing软件测试网9t/WS'y@7|xZ

0Uc2x7zF2f:M/L0(5) test开头的测试方法。

#?)Q H*j#nBx0

.Np1\skM8b/h/_*m0(6) 定义testsuite,指定testsuite要执行的测试方法

Hg-x4R#xG+`xAd-Yu0

8L M kI9DR0(7)如果要在命令行下执行测试,需要用main函数指定待运行testsuite和一系列定义,以及运行方法和运行对象等等。

,ooK{(oe0

(G)Z4I.^G9_0可以写一个类专门来集合要测试的方法或者suite,然后可以指定来运行。51Testing软件测试网W%E2FtR,sg m2t

51Testing软件测试网2k.u'\q8H$S&U$f0\6a3[

看下面一个小的范例:

"cd u7n4@uv}0

c8N'h/Ue2o0import Example.ExampleHelloTest; //因为ExampleHelloTest在另外一个包里所以需要import进来
n;g2zFj3T0import junit.framework.*;51Testing软件测试网Ed\a_z5M'P

-I]y5^Q[$[0import pragmaticUnitTest.TestLargest;//因为TestLargest在另外一个包里所以需要import进来51Testing软件测试网 wn:Ex3B;b)K
51Testing软件测试网:N;T\8^.{7f0}"S

H7}E`)f%O0public class TestSuiteComposite extends TestCase{51Testing软件测试网Jl#K5ju%L~
 public TestSuiteComposite (String  method){51Testing软件测试网2qX BS kWN|Q

51Testing软件测试网;d mT@R"u7e/o

 super(method);51Testing软件测试网Q'] KCr*]Q
 }51Testing软件测试网h)?-t.`w2])L

&zq5DY#V"f {7g"R$G+wX0/**51Testing软件测试网Z;Q!LB I4kd

51Testing软件测试网U5MaV2{M?F-U

*define composited testsuite51Testing软件测试网/m&y!p^H

51Testing软件测试网&?7K)Gj&AT5T;eC

*/

x r `0}G#t051Testing软件测试网8c9D?"Z4n!H!E:J

static public Test suite(){
2cIiFg[&t3f0  TestSuite suite = new TestSuite();

}4_/e3x!?GN:HK0

:B$Crl4BC+Z @w0// add all the test methods from ExampleHelloTest class.

S)J9Sri|2^r'U |%n0

.\KViC9CH0?z0  suite.addTestSuite(ExampleHelloTest.class);

YHw+` H X3Tt _7@051Testing软件测试网G]R#w'G-^ D

51Testing软件测试网^]}%Sq{
add test suite from TestLargest class.51Testing软件测试网:Y5~.~)x _e8J:RZ_7\.Y2z`

v GsKa#G'I,H0suite.addTest(TestLargest.suite());
Us_~sS\0  return suite;

|0v0p,k8YIYQM[H051Testing软件测试网4Os r bE I!|3?p

基本结构就是ExampleHelloTest class定义了一系列的测试方法但是没有定义test suite.这里就把这个class里的所有的测试方法加进来。然后又把TestLargest class 里定义的suite加进来。实际上在TestLargest class里定义了10个测试方法。但是TestLargest class的suite只是指定了其中的2个来运行。因此在这个composite的class里我们运行顺序是先把ExampleHelloTest定义的所有测试方法执行然后再执行TestLargest class 里suite里限定的2个测试方法。

8N2Z B\S.J'J Y4A7\051Testing软件测试网H:Ot}5F(jD9s

 51Testing软件测试网2vTT5j.v&S%O C8q+s


TAG: JUnit 单元测试

 

评分:0

我来说两句

Open Toolbar