基礎測試結構
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calc = new Calculator();
assertEquals(5, calc.add(2, 3));
}
}
- 無需
main 方法,IDE 或 Maven/Gradle 直接運行標註 @Test 的方法。
- 斷言使用
org.junit.Assert.* 靜態導入。
參數化測試
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class StringLengthTest {
private String input;
private int expected;
public StringLengthTest(String input, int expected) {
this.input = input;
this.expected = expected;
}
@Parameterized.Parameters
public static Collection
進階提示
- 使用
@Before/@After 管理資源。
- 異常測試:
@Test(expected = IllegalArgumentException.class)。
- 超時測試:
@Test(timeout = 1000)。