標籤:intellij 結構 UI 失敗 不一致 com toolbar ted time
單元測試的基本使用一、環境配置
使用idea IDE 進行單元測試,首先需要安裝JUnit 外掛程式。
1.安裝JUnit外掛程式步驟
File-->settings-->Plguins-->Browse repositories-->輸入JUnit-->選擇JUnit Generator V2.0安裝。
2.使用JUnit外掛程式
在需要進行單元測試的類中,使用快速鍵alt+insert,選擇JUnit test,選擇JUnit4。
二、單元測試
代碼Demo:
@Test public void testAdd() { assertEquals(2, new UserDao().add(1, 1)); }
1>注意事項:
1、測試方法上面必須使用@Test註解進行修飾。
2、測試方法必須使用public void 進行修飾,不能帶有任何參數。
3、建立一個原始碼目錄用來存放測試代碼。
4、測試類別的包應該與被測試類別的包保持一致。
5、測試單元中的每一個方法必須獨立測試,每個測試方法之間不能有依賴。
6、測試類別使用Test做為類名的尾碼(非必要)。
7、測試方法使用test作為方法名的首碼(非必要)。
2>錯誤解析:
1、Failure 一般是單元測試使用的斷言方法判斷失敗引起,說明預期結果和程式運行結果不一致。
2、error 是有代碼異常引起的,他產生於測試代碼本身中的Bug。
3、測試案例是不是用來證明你是對的,而是用來證明你沒有錯。
3>測試流程:
代碼Demo:
@BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void setUpAfterClass() throws Exception { } @Before public void before() throws Exception { } @After public void after() throws Exception { }
1、@BeforeClass所修飾的方法在所有方法載入前執行,而且他是靜態在類載入後就會執行該方法,
在記憶體中只有一份執行個體,適合用來載入設定檔。
2、@AfterClass所修飾的方法在所有方法執行完畢之後執行,通常用來進行資源清理,例如關閉資料庫連接。
3、@Before和@After在每個測試方法執行前都會執行一次。
4>常用註解
1、@Test(excepted=XX.class) 在運行時忽略某個異常。
2、@Test(timeout=毫秒) 允許程式啟動並執行時間。
3、@Ignore 所修飾的方法被測試器忽略。
4、RunWith 可以修改測試回合器 org.junit.runner.Runner
5>測試套件
測試套件是組織測試類別一起啟動並執行測試類別。具體如下:
代碼Demo:
@RunWith(Suite.class)@Suite.SuiteClasses({UserTest1,UserTest2,UserTest3})public class SuiteTest{ }
注意事項:
1、作為測試套件的入口類,類中不能包含任何方法。
2、更改測試回合器Suite.class。
3、將需要啟動並執行測試類別放入Suite.SuiteClasses({})的數組中。
6>參數化設定
需要測試的僅僅是測試資料,代碼結構是不變的,只需要更改測試資料。
代碼Demo:
@RunWith(Parameterized.class)public class parameterTest { int expected = 0; int input1 = 0; int input2 = 0; @Parameters public static Collection<Object[]> t() { return Arrays.asList(new Object[][]{ {3,1,2}, {5,2,3} }); } public parameterTest(int expected,int input1,int input2) { this.expected = expected; this.input1 = input1; this.input2 = input2; } @Test public void testAdd() { assertEquals(expected, UserDao.add(input1,input2)); }}
具體步驟:
1、更改預設的測試回合器為@RunWith(Parameterized.class)。
2、聲明變數來存放預期值和測試值。
3、聲明一個傳回值為Collection的公用靜態方法,並用@Parameters修飾。
4、為測試類別聲明一個帶有參數的公用建構函式,並在其中為他聲明變數賦值。
以上為基於IntelliJ IDEA 進行的單元測試。
Java:IDEA下使用JUNIT