Junit4 注解提供了书写单元测试的基本功能。.本章将介绍@BeforeClass, @AfterClass,@Before, @After 和@Tes 这几个基本t注解。
被@BeforeClass注解的方法会是:
这样的方法被用作执行计算代价很大的任务,如打开数据库连接。被@BeforeClass 注解的方法应该是静态的(即 static类型的).
被@AfterClass注解的方法应是:
该类型的方法被用作执行类似关闭数据库连接的任务。被@AfterClass 注解的方法应该是静态的(即 static类型的).
被@Before 注解的方法应是:
该类型的方法可以被用来为测试方法初始化所需的资源。
被@After注解的方法应是:
该类型的方法被用来关闭由@Before注解修饰的测试方法打开的资源。
被@Test注解的测试方法包含了真正的测试代码,并且会被Junit应用为要测试的方法。@Test注解有两个可选的参数:
<h3 style="background-color:rgb(153,204,255);""> Junit4注解例子
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>
ArithmeticTest.java Arithmetic.java的Junit单元测试类:
<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>
样例日志输出:
<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,转载请注明出处,谢谢!