> 本章介紹測試套件的概念,以及如何使用測試套件測試多個測試工用例以及使用參數設置來重復的測試代碼進行測試,提高代碼的可重用性。
1. JUnit測試套件的使用
```java
package com.dodoke;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({XXXTest.class, ...}) // 多個測試類的集合
public class SuiteTest {} // 一個空類
```
2. JUnit參數化設置
```java
package com.dodoke;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.*;
@RunWith(Parameterized.class)
public class ParameterTest {
private int expected;
private int param1;
private int param2;
@Parameters
public static Collection<Object[]> test() {
return Arrays.asList(new Object[][] {
{13, 10, 3},{20, 10, 10}
});
}
public ParameterTest(int expected, int param1, int param2) {
this.expected = expected;
this.param1 = param1;
this.param2 = param2;
}
@Test
public void testSum() {
Assert.assertEquals(expected, new Calculator().sum(param1, param2));
}
}
```