首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JUnit 4 入門:帶參數化測試的簡單示例與最佳實踐

     編輯:程式設計綜合問答

基礎測試結構

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 data() {
        return Arrays.asList(new Object[][]{
            {"hello", 5}, {"world", 5}, {"", 0}, {null, 0}
        });
    }

    @Test
    public void testLength() {
        assertEquals(expected, (input == null) ? 0 : input.length());
    }
}

進階提示

  • 使用 @Before/@After 管理資源。
  • 異常測試:@Test(expected = IllegalArgumentException.class)。
  • 超時測試:@Test(timeout = 1000)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved