JUnit教程 -- JUnit注解

来源:互联网 发布:聚宝盆时时彩计划软件 编辑:程序博客网 时间:2024/05/16 05:24

在本节中,我们将提到支持在JUnit4基本注释,下表列出了这些注释的概括:注解描述@Test
public void method()测试注释指示该公共无效方法它所附着可以作为一个测试用例。@Before
public void method()Before注释表示,该方法必须在类中的每个测试之前执行,以便执行测试某些必要的先决条件。@BeforeClass
public static void method()BeforeClass注释指出这是附着在静态方法必须执行一次并在类的所有测试之前。发生这种情况时一般是测试计算共享配置方法(如连接到数据库)。@After
public void method()After 注释指示,该方法在执行每项测试后执行(如执行每一个测试后重置某些变量,删除临时变量等)@AfterClass
public static void method()当需要执行所有的测试在JUnit测试用例类后执行,AfterClass注解可以使用以清理建立方法,(从数据库如断开连接)。注意:附有此批注(类似于BeforeClass)的方法必须定义为静态。@Ignore
public static void method()当想暂时禁用特定的测试执行可以使用忽略注释。每个被注解为@Ignore的方法将不被执行。

 
让我们看看一个测试类,在上面提到的一些注解的一个例子。

AnnotationsTest.java

package com.yiibai.junit;import static org.junit.Assert.*;import java.util.*;import org.junit.*;public class AnnotationsTest {private ArrayList testList;@BeforeClasspublic static void onceExecutedBeforeAll() {System.out.println("@BeforeClass: onceExecutedBeforeAll");}@Beforepublic void executedBeforeEach() {testList = new ArrayList();System.out.println("@Before: executedBeforeEach");}@AfterClasspublic static void onceExecutedAfterAll() {System.out.println("@AfterClass: onceExecutedAfterAll");}@Afterpublic void executedAfterEach() {testList.clear();System.out.println("@After: executedAfterEach");}@Testpublic void EmptyCollection() {assertTrue(testList.isEmpty());System.out.println("@Test: EmptyArrayList");}@Testpublic void OneItemCollection() {testList.add("oneItem");assertEquals(1, testList.size());System.out.println("@Test: OneItemArrayList");}@Ignorepublic void executionIgnored() {System.out.println("@Ignore: This execution is ignored");}}

如果我们运行上面的测试,控制台输出将是以下几点:

@BeforeClass: onceExecutedBeforeAll@Before: executedBeforeEach@Test: EmptyArrayList@After: executedAfterEach@Before: executedBeforeEach@Test: OneItemArrayList@After: executedAfterEach@AfterClass: onceExecutedAfterAll
1 0
原创粉丝点击