Junit - 基础注解(@BeforeClass、@Before、@Test、@After、@AfterClass)

Junit4 注解提供了书写单元测试的基本功能。本章将介绍@BeforeClass,@AfterClass,@Before,@After,@Test 这几个基本注解。

@BeforeClass注解
被@BeforeClass注解的方法会是:
只被执行一次
运行junit测试类时第一个被执行的方法
这样的方法被用作执行计算代价很大的任务,如打开数据库连接。被@BeforeClass 注解的方法应该是静态的(即 static类型的)。
@AfterClass注解
被@AfterClass注解的方法应是:

只被执行一次
运行junit测试类是最后一个被执行的方法
该类型的方法被用作执行类似关闭数据库连接的任务。被@AfterClass 注解的方法应该是静态的(即 static类型的)。
@Before注解
被@Before 注解的方法应是:
junit测试类中的任意一个测试方法执行 前 都会执行此方法
该类型的方法可以被用来为测试方法初始化所需的资源。
@After注解
被@After注解的方法应是:
junit测试类中的任意一个测试方法执行后 都会执行此方法, 即使被@Test 或 @Before修饰的测试方法抛出异常
该类型的方法被用来关闭由@Before注解修饰的测试方法打开的资源。
@Test 注解
被@Test注解的测试方法包含了真正的测试代码,并且会被Junit应用为要测试的方法。@Test注解有两个可选的参数:
expected 表示此测试方法执行后应该抛出的异常,(值是异常名)
timeout 检测测试方法的执行时间

Junit 4 注解例子
Arithmetic.java,本例要用到的需要Junit进行单元测试的类:
package in.co.javatutorials;

public class Arithmetic {

public int add(int i, int j) {
    return i + j;
}

}
ArithmeticTest.java,Arithmetic.java的Junit单元测试类:

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");
}

}
样例结果输出

本例在Eclipse Junit窗口的输出结果如下:

样例日志输出:

@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

posted @ 2020-04-29 21:51  小辣椒樱桃  阅读(654)  评论(0编辑  收藏  举报