Junit 4 單元測試常規內容簡介

對代碼測試的正確理解:

測試用例用來達到想要的預期結果,可是對於邏輯錯誤無能爲力;測試用例不是用來證實你是對的,而是用來證實你是沒錯的。java

注意以及建議事項:數據庫

一、測試方法上必須使用@Test進行修飾。api

二、測試方法必須使用public void進行修飾,不能帶任何的參數。異步

三、儘可能將測試類放在一個單獨的源代碼目錄中,儘可能不要放在源程序文件目錄(僅僅是我的建議)。ide

四、測試類的包應該和被測試類保持一致。函數

五、測試單元中的每一個方法必須能夠獨立測試,測試方法間不能有任何依賴。單元測試

測試過程當中常見錯誤測試

一、Failure通常由單元測試使用的斷言方法判斷失敗所引發的,這表示測試點發現了問題,就是說程序輸出的結果和咱們預期的結果不同。ui

二、Error是由代碼異常引發的,它能夠產生於測試代碼自己的錯誤,也能夠是被測試代碼中的一個隱藏bug。this

Junit運行流程以及常見註解:

一、@BeforeAll / BeforeClass:修飾的方法會在全部方法被調用前執行,而且該方法是靜態的,因此當測試類被加載後接着運行。

二、@AfterAll / AfterClass:修飾的方式一般用來對資源的清理,如關閉數據庫的鏈接。

三、@BeforeEach / Before:會在每一個測試方法執行前執行一次。

四、@AfterEach / After:會在每一個測試方法執行後執行一次。

五、@Ignore:所修飾的測試方法會被測試運行器忽略

六、@RunWith:能夠更改測試運行器 org.junit.runner.Runner

七、@RunWith(Suite.class):聲明套件運行器,若是是須要多個單元測試類整合測試 使用一個Runner進行異步測試,只須要把相關的class放入到SuiteClasses{}中便可

八、參數化設置:須要測試的僅僅是測試數據,代碼結構是不變的,只須要更改測試數據。

具體步驟:(1)、更改默認的測試運行器爲@RunWith(Parameterized.class)。

(2)、聲明變量來存放預期值和測試值。

(3)、聲明一個返回值爲Collection的公共靜態方法,並用@Parameters修飾。

(4)、爲測試類聲明一個帶有參數的公共構造函數,並在其中爲他聲明變量賦值。

package com.CalculateTest;

import static org.junit.jupiter.api.Assertions.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import com.Calculate.Calculate;

@RunWith(Parameterized.class)

public class ParameteriTest {
	
	int expected = 0;;
	int input1 = 0;
	int input2 = 0;
	
	@Parameters
	public static Collection<Object[]> t(){
		
		return Arrays.asList(new Object[][] {
				{3,1,2},
				{4,2,2}
		});
	}
	
	public ParameteriTest(int expected, int input1, int input2) {
		// TODO Auto-generated constructor stub
		
		this.expected = expected;
		this.input1 = input1;
		this.input2 = input2;
	}

	@Test
	public void testAdd() {
		fail("Not yet implemented");
		
		assertEquals(expected, new Calculate().add(input1, input2));
	}

}

九、@Test(expected=XX.class)捕獲拋出異常

十、@Test(timeout=XX毫秒)限制方法的運行時效

相關文章
相關標籤/搜索