编写一个稍微复杂的类并使用junit来测试
时间: 2023-06-15 22:06:39 浏览: 49
假设我们要编写一个银行账户类,这个类具有存款、取款、查询余额等功能。
```java
public class BankAccount {
private double balance;
public BankAccount(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if (balance < amount) {
throw new InsufficientFundsException("Not enough balance");
}
balance -= amount;
}
}
```
接下来我们可以使用JUnit来编写测试用例来测试这个类的功能是否正常。
```java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
public class BankAccountTest {
@Test
public void testGetBalance() {
BankAccount account = new BankAccount(1000);
assertEquals(1000, account.getBalance(), 0);
}
@Test
public void testDeposit() {
BankAccount account = new BankAccount(1000);
account.deposit(500);
assertEquals(1500, account.getBalance(), 0);
}
@Test
public void testWithdraw() throws InsufficientFundsException {
BankAccount account = new BankAccount(1000);
account.withdraw(500);
assertEquals(500, account.getBalance(), 0);
}
@Test
public void testWithdrawWithInsufficientFundsException() {
BankAccount account = new BankAccount(1000);
assertThrows(InsufficientFundsException.class, () -> account.withdraw(1500));
}
}
```
我们可以看到,使用JUnit可以非常方便地对类的功能进行测试,确保其正常运行。