Java 學習記錄108 — Parameterized Testing

張小雄
4 min readJan 24, 2022

--

今天要學的是把測試方法加上參數的應用

BankAccountTestParameterized.java

package bankAcoount;import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;@RunWith(Parameterized.class)
public class BankAccountTestParameterized {
private BankAccount account;
private double amount;
private boolean branch;
private double expected;
public BankAccountTestParameterized(double amount, boolean branch, double expected) {
this.amount = amount;
this.branch = branch;
this.expected = expected;
}
@Before
public void setup() {
account = new BankAccount("Tim", "Jimmy", 1000.00, BankAccount.CHECKING);
System.out.println("Running a test...");
}
@Parameterized.Parameters
public static Collection<Object[]> testConditions() {
return Arrays.asList(new Object[][]{
{100.00, true, 1100.00},
{200.00, true, 1200.00},
{325.14, true, 1325.14},
{489.33, true, 1489.33},
{1000.00, true, 2000.00},
});
}
@Test
public void getBalance_deposit() {
account.deposit(amount, branch);
assertEquals(expected, account.getBalance(), 0);
}
}

測試結果:

Running a test…

Running a test…

Running a test…

java.lang.AssertionError:

Expected :1325.14

Actual :1325.1399999999999

<Click to see difference>

at org.junit.Assert.fail(Assert.java:89)

at org.junit.Assert.failNotEquals(Assert.java:835)

Running a test…

Running a test…

看起來複雜了一些,但其實還好

我們設定的參數就在 testConditions() 裡面

其他就是 filedconstrucetor

還有 setup() (每個測試案例都會運行一次)

這些測試數據傳給測試案例 getBalance_deposit()

裡面報了一個錯,因為 double 的關係,有時候會有這個誤差

修正的方法也很簡單

@Test
public void getBalance_deposit() {
account.deposit(amount, branch);
assertEquals(expected, account.getBalance(), 0.1);
}

assertEquals() 第三個參數 delta 增加一點就好

只要符合這個誤差值內就算通過

測試結果:

全部通過

上面代碼全都紀錄在我的 Github

--

--

張小雄
張小雄

Written by 張小雄

記錄成為軟體工程師的過程

No responses yet