Junit4使用教程詳解

  • 下載Junit4相關Jar包(一般eclipse等IDE已經集成):

資源鏈接:

https://download.csdn.net/download/yl405001832/11580748

  • 將jar包導入項目

右鍵點擊項目,點擊Build Path選擇 Configure Build Path

 

如果採用eclipse集成的jar包:

 

如果採用自己下載的jar包:

 

  • 使用Junit的最佳實踐:

1) 新建一個名爲test的source folder,用於存放測試類源代碼。

2) 目標類與測試類應該位於同一個包下面,這樣測試類中就不必導入源代碼所在的包,因爲他們位於同一個包下面。

3) 在一個測試類中,所有被@Test註解所修飾的public,void方法都是test case,可以被JUnit所執行。

4) 雖然JUnit4並不要求方法名以test開頭,但是我們最好還是按照JUnit3.8的要求那樣,以test作爲測試方法名的開頭。

 

  • Junit4註解詳解:

@Test:

  1. 定義:

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.METHOD})

public @interface Test

  1. 所有被@Test註解所修飾的public,void方法都是test case,可以被JUnit所執行。
  2. 可選的expected爲一個繼承自Throwable的Class對象,如果@Test加上這個屬性,表示Junite期待相關的test case 拋出該Throwable異常,如果沒有拋出該異常,則單元測試failure.

代碼示例:

  1. 可選的timeout爲一個long類型,如果@Test加上這個屬性,表示Junite期待相關的test case 運行的時間不超過該數值,否則則單元測試failure。

代碼示例:

 

@Before:

  1. 定義:

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface Before

  1. 所有被@Before註解所修飾的public, void方法將會在每個test case執行之前執行:一般對於test case都需要執行的初始化操作可以放到這個方法裏面,比如創建輸入、輸出流。

代碼示例:

 

@After:

  1. 定義:

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface After

所有被@After註解所修飾的public, void方法將會在每個test case執行之後執行:一般對於所有test case執行完畢後需要處理的邏輯可以放到這個方法裏面,比如關閉輸入、輸出流。

代碼示例:

 

@BeforeClass:

  1. 定義:

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface BeforeClass

  1. 所有被@BeforeClass註解所修飾的方法必須爲:public, static,void且無參數。對於整個測試類需要統一初始化處理的邏輯放到這個方法裏,比如創建數據庫連接等。

代碼示例:

 

@AfterClass:

  1. 定義:

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface AfterClass

  1. 所有被@AfterClass註解所修飾的方法必須爲:public, static,void且無參數。對於整個測試類需要統一善後處理的邏輯放到這個方法裏,比如關閉數據庫連接等。

代碼示例:

@Ignore:

  1. 定義:

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.METHOD, ElementType.TYPE})

public @interface Ignore

  1. @Ignore註解可用於修飾方法,也可以用於修飾類。
  2. 所有被@Ignore修飾的test case,將不會被JUnit所執行。
  3. @Ignore修飾在類上,表示該類下的所有test case都不會被執行。
  4. 可選的value爲一個String類型參數,可以提示下用戶。
  5. 代碼示例:

代碼示例:

  1. 待測試的類:Calculator.java

package test;

 

public class Calculator {

   public int add(int a, int b) {

      try {

        Thread.sleep(500);

      } catch (InterruptedException e) {

        e.printStackTrace();

      }

      return a + b;

   }

  

   public int subtract(int a, int b) {

      return a - b;

   }

  

   public int multiply(int a, int b) {

      return a * b;

   }

  

   public int divide(int a, int b) throws Exception {

      if(0 == b)

        throw new Exception("除數不能爲0");

      return a / b;

   }

  

}

 

  1. 測試類:CalculatorTest.java

package test;

 

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.Ignore;

import org.junit.Test;

 

public class CalculatorTest {

   private Calculator cal;

  

   @BeforeClass

   public static void globalInit() {

      System.out.println("globalInit invoked!");

   }

  

   @AfterClass

   public static void globalDestroy() {

      System.out.println("globalDestroy invoked!");

   }

  

   @Before

   public void setUp() {

      cal = new Calculator();

      System.out.println("before");

   }

  

   @After

   public void tearDown() {

      System.out.println("after");

   }

 

   @Test(timeout = 600)

   @Ignore("哎呦,還沒想好怎麼測試呢!")

   public void testAdd() {

      int result = cal.add(3, 5);

      assertEquals(8, result);

   }

 

   @Test

   public void testSubtract() {

      int result = cal.subtract(1, 6);

      assertEquals(-5, result);

   }

  

   @Test

   public void testMultiply() {

      int result = cal.multiply(5, 9);

   }

  

   @Test(expected = Exception.class)

   public void testDivide() throws Exception {

      cal.divide(1, 0);

   }

  

}

  • Junit4參數化測試(Parameters)詳解:
  1. 參數化測試(Parameters):當一個測試類使用參數化運行器運行時,需要在類的聲明處加上@RunWith(Parameterized.class)註解,表示該類將不使用JUnit內建的運行器運行,而使用參數化運行器運行;在參數化運行類中提供參數的方法(該方法爲public static類型)上要使用@Parameters註解來修飾,同時在測試類的構造方法中爲各個參數賦值(構造方法是由JUnit調用的),最後編寫測試類,它會根據參數的組數來運行測試多次。
  2. 代碼示例:

參數化測試類:ParametersTest.java

package test;

 

import static org.junit.Assert.*;

import java.util.Arrays;

import java.util.Collection;

 

import org.junit.Before;

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 ParametersTest {

   private int expected;

   private int input1;

   private int input2;

   private Calculator cal = null;

 

   @SuppressWarnings("unchecked")

   @Parameters

   public static Collection preparaData() {

      Object[][] object = { { 3, 1, 2 }, { -4, -1, -3 }, { 5, 2, 3 },

           { 4, -4, 8 } };

      return Arrays.asList(object);

   }

  

   public ParametersTest(int expected, int input1, int input2) {

      this.expected = expected;

      this.input1 = input1;

      this.input2 = input2;

   }

  

   @Before

   public void setUp() {

      cal = new Calculator();

   }

  

   @Test

   public void testAdd() {

      assertEquals(this.expected, cal.add(this.input1, this.input2));

   }

  

}

 

  • Junit4套件測試(Suit)詳解:
  1. 在JUnit 4中,如果想要同時運行多個測試,需要使用兩個註解:@RunWith(Suite.class)以及@Suite.SuiteClasses(),通過這兩個註解分別指定使用Suite運行器來運行測試,以及指定了運行哪些測試類,其中的@SuiteClasses中可以繼續指定Suite,這樣JUnit會再去尋找裏面的測試類,一直找到能夠執行的Test Case並執行之。
  2. 代碼示例:

參數化測試類:TestAll.java

package test;

 

import org.junit.runner.RunWith;

import org.junit.runners.Suite;

 

/**

 * @author liangxiong

 * Using Suite as a runner allows you to manually build a

 * suite containing tests from many classes. It is the JUnit 4

 * equivalent of the JUnit 3.8.x static Test suite() method. To use it,

 * annotate a class with @RunWith(Suite.class) and

 * @SuiteClasses(TestClass1.class, ...). When you run this class, it will run

 * all the tests in all the suite classes

 *

 */

@RunWith(Suite.class)

@Suite.SuiteClasses( { CalculatorTest.class, LargestTest.class,

ParametersTest.class })

// 類名不重要,主要看註解!

public class TestAll {

 

}

 

補充Largest.java以及LargestTest.java

package test;

 

public class Largest {

   public int getLargest(int[] array) throws Exception {

      if(null == array || 0 == array.length) {

        throw new Exception("數組不能爲空");

      }

      int result = array[0];

     

      for(int i = 0; i < array.length; i++) {

        if(result < array[i])

           result = array[i];

      }

      System.out.println(result);

      return result;

   }

}

package test;

 

import static org.junit.Assert.fail;

import org.junit.After;

import org.junit.Before;

import org.junit.Test;

 

public class LargestTest {

  

   private Largest largest;

   @Before

   public void setUp() throws Exception {

      largest = new Largest();

   }

 

   @After

   public void tearDown() throws Exception {

   }

 

   @Test

   public void testGetLargest() {

      int[] array = {1, 9, -10, -20, 23, 34};

      try {

        largest.getLargest(array);

      } catch (Exception e) {

        fail("測試失敗");

      }

   }

  

   @Test(expected = Exception.class)

// @Ignore

   public void testGetLargest2() throws Exception {

      largest.getLargest(null);

   }

  

   @Test(expected = Exception.class)

   public void testGetLargest3() throws Exception {

      largest.getLargest(new int[] {});

   }

 

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章