Junit4 注解提供了书写单元测试的基本功能。.本章将介绍@BeforeClass, @AfterClass,@Before, @After 和@Tes 这几个基本t注解。
@BeforeClass注解
@AfterClass注解
@Before注解
@After注解
教程目录导航
@BeforeClass注解
被@BeforeClass注解的方法会是:这样的方法被用作执行计算代价很大的任务,如打开数据库连接。被@BeforeClass 注解的方法应该是静态的(即 static类型的).
- 只被执行一次
- 运行junit测试类时第一个被执行的方法
@AfterClass注解
被@AfterClass注解的方法应是:
该类型的方法被用作执行类似关闭数据库连接的任务。被@AfterClass 注解的方法应该是静态的(即 static类型的).
- 只被执行一次
- 运行junit测试类是最后一个被执行的方法
@Before注解
被@Before 注解的方法应是:该类型的方法可以被用来为测试方法初始化所需的资源。
- junit测试类中的任意一个测试方法执行 前 都会执行此方法
@After注解
被@After注解的方法应是:该类型的方法被用来关闭由@Before注解修饰的测试方法打开的资源。
- junit测试类中的任意一个测试方法执行后 都会执行此方法, 即使被@Test 或 @Before修饰的测试方法抛出异常
@Test 注解
被@Test注解的测试方法包含了真正的测试代码,并且会被Junit应用为要测试的方法。@Test注解有两个可选的参数:<h3 style="background-color:rgb(153,204,255);""> Junit4注解例子
- expected 表示此测试方法执行后应该抛出的异常,(值是异常名)
- timeout 检测测试方法的执行时间
Arithmetic.java,本例要用到的需要Junit进行单元测试的类:
ArithmeticTest.java Arithmetic.java的Junit单元测试类:<span style="font-family:Microsoft YaHei;font-size:12px;">package in.co.javatutorials; public class Arithmetic { public int add(int i, int j) { return i + j; } }</span>
<span style="font-family:Microsoft YaHei;font-size:12px;">package in.co.javatutorials; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class ArithmeticTest { @BeforeClass public static void setUpClass() { // one time setup method System.out.println("@BeforeClass - executed only one time and is first method to be executed"); } @AfterClass public static void tearDownClass() { // one time tear down method System.out.println("@AfterClass - executed only one time and is last method to be executed"); } @Before public void setUp() { // set up method executed before every test method System.out.println("@Before - executed before every test method"); } @After public void tearDown() { // tear down method executed after every test method System.out.println("@After - executed after every test method"); } @Test public void testAdd() { Arithmetic arithmetic = new Arithmetic(); int actualResult = arithmetic.add(3, 4); int expectedResult = 7; assertEquals(expectedResult, actualResult); System.out.println("@Test - defines test method"); } }</span>
样例结果输出
本例在Eclipse Junit窗口的输出结果如下:
样例日志输出:
<span style="font-family:Microsoft YaHei;font-size:12px;">@BeforeClass - executed only one time and is first method to be executed @Before - executed before every test method @Test - defines test method @After - executed after every test method @AfterClass - executed only one time and is last method to be executed</span>
源码下载
教程目录导航
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
本文出处为 http://blog.csdn.net/luanlouis,转载请注明出处,谢谢!