Testing ensures that a method behaves as expected under the conditions specified in its REQUIRES, MODIFIES, and EFFECTS clauses.
// REQUIRES: dx > 0
// MODIFIES: this
// EFFECTS: adds dx to x coordinate
public void move(int dx) { ... }
Since
dx > 0is required, test cases should only include positive values ofdx. Values ofdx <= 0should not be tested.
If a method works for 0
x = 0 (minimum boundary)x = 100 (maximum boundary)x = 50 (midpoint, typical case)public class BankAccount {
private double balance;
private String owner;
// REQUIRES: initialBalance >= 0
// EFFECTS: Initializes a bank account with the given owner name
// and starting balance
public BankAccount(String owner, double initialBalance) {
this.owner = owner;
this.balance = initialBalance;
}
// REQUIRES: amount > 0 && amount <= balance
// MODIFIES: this
// EFFECTS: Deducts the given amount from the balance
public void withdraw(double amount) {
this.balance -= amount;
}
// EFFECTS: Returns the current balance of the account
public double getBalance() {
return this.balance;
}
}
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class BankAccountTest {
private BankAccount acc;
@BeforeEach
void setUp() {
acc = new BankAccount("Alice", 100);
}
@Test
void testWithdraw() {
acc.withdraw(30);
assertEquals(70, acc.getBalance());
acc.withdraw(20);
assertEquals(50, acc.getBalance());
acc.withdraw(50);
assertEquals(0, acc.getBalance());
}
}
The test ensures that the
withdrawMethod consistently reduces the balance as expected.