Junit4.x单元测试的使用
参考文档:Junit Cookbook[*]单元测试的执行顺序是初始化-->测试-->销毁。在Junit4中添加了Annotation,使单元测试变得更加简单了,只需要在方法前添加相应的注解来完成单元测试的三个过程。
org.junit.Before:注解为初始化方法。
org.junit.BeforeClass:注解初始化静态方法,并只运行一次。
org.junit.After:注解为销毁方法。
org.junit.AfterClass:注解销毁静态方法,并只运行一次。
org.junit.Test:注解为测试方法。
[*]在单元测试的整个过程中,可以添加断言来审查运行过程。Junit提供了方便类org.junit.Assert提供这一功能。
[*]运行单元测试有两种途径:
1.在java的main方法中调用
org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...); 2.在dos命令行中运行
java org.junit.runner.JUnitCore TestClass1 [...other test classes...]
[*]在测试过程中,可以放弃捕捉你所期望的异常,如
@Test(expected= IndexOutOfBoundsException.class)
[*]实例:
package com.sin90;import org.junit.Before;import org.junit.After;import org.junit.Test;import java.util.ArrayList;import static org.junit.Assert.*;public class JunitTest {private String a;private String b;@Beforepublic void setup(){a="a";b="b";}@Test(expected=IndexOutOfBoundsException.class)public void testString(){assertTrue("a".equals(a));assertTrue("b".equals(b));new ArrayList().get(0);}@Afterpublic void destroy(){a=null;b=null;assertNull(a);assertNull(b);}public static void main(String[] args) {org.junit.runner.JUnitCore.runClasses(JunitTest.class);}}
页:
[1]