public class AccountModel extends AbstractModel {
public static BigDecimal balance = new BigDecimal(0.00);
public static BigDecimal balanceEuro = new BigDecimal(0.00);
public static BigDecimal balanceYen = new BigDecimal(0.00);
// deposit method
public static BigDecimal deposit(double amount) {
balance = balance.add(new BigDecimal(amount));
return balance;
}
// withdraw method
public static void withdraw(BigDecimal withdraw) {
balance = balance.subtract(withdraw);
}
public static BigDecimal euro() {
balanceEuro = balance.multiply(new BigDecimal(0.79));
return balanceEuro;
}
public static BigDecimal yen() {
balanceYen = balance.multiply(new BigDecimal(94.1));
return balanceYen;
}
public static BigDecimal balance() {
return balance;
}
@Override
public void notifyChange(ModelEvent me) {
// TODO Auto-generated method stub
}
}
public class AccountModelTest {
AccountModel accTest = new AccountModel();
// test deposit method
@Test
public void testDeposit() {
// BigDecimal balance = new BigDecimal(0.00);
System.out.println("Deposit");
accTest.deposit(30.00);
accTest.deposit(100.00);
// excepted balance
BigDecimal expectedBalance = new BigDecimal(130.00);
System.out.println("Expected: " + expectedBalance.setScale(2, BigDecimal.ROUND_HALF_DOWN) + " Actual: "
+ accTest.balance().setScale(2, BigDecimal.ROUND_HALF_DOWN));
BigDecimal balance = new BigDecimal(0.00);
assertEquals(expectedBalance.setScale(2, BigDecimal.ROUND_HALF_DOWN),
accTest.balance().setScale(2, BigDecimal.ROUND_HALF_DOWN));
System.out.println("");
}
// test withdraw method
@Test
public void testWithdraw() {
System.out.println("Withdraw");
AccountModel accTest1 = new AccountModel();
accTest1.deposit(40.00);
accTest1.withdraw(new BigDecimal(30.00));
BigDecimal expectedBalance1 = new BigDecimal(10.00);
System.out.println("Expected: " + expectedBalance1.setScale(2, BigDecimal.ROUND_HALF_DOWN) + " Actual: "
+ accTest1.balance().setScale(2, BigDecimal.ROUND_HALF_DOWN));
assertEquals(expectedBalance1.setScale(2, BigDecimal.ROUND_HALF_DOWN),
accTest1.balance().setScale(2, BigDecimal.ROUND_HALF_DOWN));
}
}
所以我正在为提取方法和存款方法做两个单独的测试用例。当我实现1个测试用例时,deposit方法工作正常,而withdraw方法工作正常。但是当我像上面显示的那样运行测试时,测试总是失败。输出是
提款 预期:10.00实际:10.00
存款 预期:130.00实际:140.00(应为130.00)
答案 0 :(得分:2)
由于您在AccountModel
类中使用静态字段,因此它们的值在所有AccountModel
实例之间共享。将它们设为非静态私有:
private BigDecimal balance = BigDecimal.ZERO;
private BigDecimal balanceEuro = BigDecimal.ZERO;
private BigDecimal balanceYen = BigDecimal.ZERO;
JUnit正在使用新的AccountModelTest
为每个@Test
创建AccountModel
类的新实例,因此每个测试的起始余额将为零。
答案 1 :(得分:1)
每个测试节目都在干净的背景下运行,您与多个测试共享AccountModel accTest
。您应该在每次测试运行时设置并清理上下文。
public class AccountModelTest {
AccountModel accTest;
@Before // this code will run before any test start, it will create new model for each test
void setUp() {
AccountModel accTest = new AccountModel();
}