二 【單元測試】Junit 4--eclipse配置Junit+Junit基礎注解( 二 )


1.2.1.7 示例import static org.junit.Assert.*;import org.junit.After;import org.junit.Before;import org.junit.Test;public class DemoTest { @BeforeClass public static void setup()throws Exception {// 這里初始化資源(如連接數據庫) } @AfterClass public static void tearDown()throws Exception {// 關閉資源() } @Before public void setUp() throws Exception {System.out.println("SetUp.....");// 這里初始化我們所需要的資源 } @After public void tearDown() throws Exception {System.out.println("Gone.....");// 這里關閉我們的資源 } @Test public void test01() {// 測試1 } @Ignore @Test public void test02() {// 測試2 }}1.2.2 打包測試Suite相關的注解1.2.2.1 @RunWith(Suite.class)需要一個特殊的Runner, 因此需要向@RunWith注解傳遞一個參數Suite.calss 。
1.2.2.2 @Suite.SuiteClasses(...{xx.class, xx.class, ...})用來表明這個類是一個打包測試類,把需要打包的類作為參數傳遞給該注解即可 。
1.2.2.3 示例有了這兩個注解之后 , 就已經完整的表達了所有的含義,因此下面的類無關緊要,隨便起個類名,內容為空
import org.junit.runner.RunWith;import org.junit.runners.Suite;import org.junit.runners.Suite.SuiteClasses;public class DemoTest { @RunWith(Suite.class) @SuiteClasses({Demo01.class, Demo02.class, Demo03.class}) public class AllTests { }}1.2.3 參數化測試相關的注解1.2.3.1 @RunWith(Parameterized.class)首先要為這種測試專門生成一個新的類,而不能與其他測試共用同一個類 。
這里不使用默認的Runner了,使用帶有參數化功能的Runner 。
@RunWith(Parameterized.class)這條語句就是為這個類指定了ParameterizedRunner 。
這個需要和我們后面的@Parameters組合使用
1.2.3.2 @Parameters放在方法上 。
定義一個待測試的類 , 并且定義兩個變量,一個用于存放參數,一個用于存放期待的結果 。
定義測試數據的結合,就是下方的prepareData()方法,該方法可以任意命名,但是必須使用@Parameters標注進行修飾 。
這里需要注意:其中的數據是一個二維數組,數據兩兩一組 , 每組中的這兩個數據,一個是參數,一個是預期的結果 。比如第一組{2,4}中:2是參數 , 4是預期結果 。這兩數據順序無所謂 。
然后 , 是構造函數,其功能就是對先前定義的兩個參數進行初始化 。這里要注意參數的順序,要和上面的數據集合的順序保持一致 。(比如都是先參數后結果)
那么這里我們還是看下面的例子吧
1.2.3.3 示例import static org.junit.Assert.assertEquals;import java.util.Arrays;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.Parameterized;import org.junit.runners.Parameterized.Parameters;@RunWith(Parameterized.class)public class FibonacciTest {@Parameters(name = "{index}: fib({0})={1}")public static Iterable<Object[]> data() {return Arrays.asList(new Object[][] {{ 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }});}private int input;private int expected;public FibonacciTest(int input, int expected) {this.input = input;this.expected = expected;}@Testpublic void test() {assertEquals(expected, Fibonacci.compute(input));}}1.2.4 控制用例執行順序相關的注解1.2.4.1 @FixMethodOrder控制測試方法的執行順序的 。
該注解的參數是org.junit.runners.MethodSorters對象 。
枚舉類org.junit.runners.MethodSorters中定義三種順序類型:
MethodSorters.JVM:按照JVM得到的方法順序,即代碼中定義的方法順序 。
MethodSorters.DEFAULT:默認的順序,以確定但不可預期的順序執行 。
MethodSorters.NAME_ASCENDING:按方法名字母順序執行 。
1.2.5 自定義規則Rule相關的注解1.2.5.1 @Rule和@ClassRule

  1. 什么是Rule實現
    Rule是一組實現了TestRule接口的共享類,提供了驗證,監視TestCase和外部資源管理等能力 。
    即,提供了測試用例執行過程中一些通用功能的共享能力,使不必重復編寫一些功能類似的代碼 。
  2. JUnit4中包含兩個注解:@Rule和@ClassRule
    用于修飾Field或返回Rule的Method 。
兩者作用域不同:
  • @Rule的作用域是測試方法 。
  • @ClassRule則是測試Class 。
1.2.5.2 JUnit提供了以下幾個Rule實現,必要時也可以自己實現Rule