因為工作關係需要在 IntelliJ 上進行開發與單元測試。本篇文章簡單紀錄從新專案開始,如何加入 JUnit 套件與第一個 JUnit Test Case (若您已經有專案,可以跳到步驟3),讓有興趣的朋友參考,謝謝。
步驟 1. 開啟 IntelliJ,點選 New Project
選擇Gradle,勾選 Java,點選下一步
輸入專案名稱 Demo,點選完成
等待專案建立完成,應該可以看到專案結構左圖
步驟 2. 右鍵點選 Java資料夾 > New > Java Class
修改 Calculation.java 如下
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Calculation { | |
public int add (int a, int b) { | |
return a + b; | |
} | |
public int sub (int a, int b) { | |
return a - b; | |
} | |
} |
步驟 3. 接下來,我們要加入測試程式,右鍵點選 Calculation > Generate
選擇 Test
更改名稱CalculationUnitTests 勾選要測試的方法,點選 OK
完成後你的測試程式 CalculationUnitTests.java 應該如下圖所示
步驟 5. 我們修改 CalculationUnitTests 如下
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
void testAdd() { | |
Calculation cal = new Calculation(); | |
int actual = cal.add(1, 2); | |
assertEquals(3, actual); | |
} | |
@Test | |
void testSub() { | |
Calculation cal = new Calculation(); | |
int actual = cal.sub(3, 2); | |
assertEquals(1, actual); | |
} |
右鍵點選測試類別,點選 Run CalculationUnitTest執行測試程式
0 留言