> 本章以一個具體的實例來介紹如何在 IntelliJ IDEA 中如何創建 JUnit4 單元測試,以及 JUnit4 視圖的使用說明
1. JUnit4快速入門
```java
package com.dodoke;
/**
* 整數計算器類
*/
public class Calculator {
public long sum(int a, int b) {
return a + b;
}
public long subtract(int a, int b) {
return a - b;
}
public long multiply(int a, int b) {
return a * b;
}
public double divide(int a, int b) {
return a / b;
}
}
```
```java
package com.dodoke;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* 計算器測試類
*/
public class CalculatorTest {
// 測試加法
@Test
public void testSum() throws Exception {
Calculator calculator = new Calculator();
long result = calculator.sum(10, 3);
// 斷言:assertEquals(expected, result), 比較預期值和實際結果
Assert.assertEquals(13L, result);
}
}
```