--- tags: intellij-idea, java --- # 10. 使用JUnit5測試程式的操作步驟 (IDEA教學 #10) 寫完考卷總要多次檢查、反覆驗算才能安心交卷。編寫程式完成後,更是要多方測試,以確保程式的運行是符合需求且能正確執行的。Java的環境裡有不少測試框架,今天要操作的是老牌的JUnit。 ### IDEA建立JUnit 5測試的步驟 1. 在類別名稱上按〔Alt+Enter〕;游標停留在類別名稱、方法名稱或變數名稱上時,按下〔Alt+Enter〕讓IDEA顯示可供操作的工作項目(Context Actions) 2. 點擊 【Create Test】:若有找不到JUnit 5 library訊息時按〔Fix〕以下載Junit相關檔案 3. 檢查【Project Structure】裡Calculator模組的Dependencies列出的Junit5.4的使用範圍(Scope),確認是【Compile】 4. Compile and test ### CalculatorTest ```java= package jdev.tw; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class CalculatorTest { Calculator calc = new Calculator(); // Annotation 註解 @BeforeEach void setUp() { System.out.println("@@CalculatorTest.setUp #12: setUp"); calc.setTotal(0); } @AfterEach void tearDown() { System.out.println("@@CalculatorTest.tearDown #19:calc.getTotal()=" + calc.getTotal()); System.out.println("@@CalculatorTest.tearDown #19: tearDown"); } // Test case @Test void add() { calc.add(100); calc.add(200); calc.add(300); Assertions.assertEquals(500, calc.getTotal()); } @Test void subtract() { calc.setTotal(1000); calc.subtract(100); calc.subtract(200); Assertions.assertEquals(700, calc.getTotal()); } } ``` ### 解說影片 <iframe width="600" height="350" src="http://jdev.tw/files/intellij-idea/idea-files.html" allowfullscreen></iframe> ##
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up