我可以写什么,这样我就可以测试从我的计数中抽钱



我试图编写一个测试函数的 xunit 测试,如果成功,函数应该返回 true,否则返回 false。

我可以写入单元测试,只是测试我是否输入一个值!我该怎么写,以便我可以测试如果我提取超过存款,那么它会返回假?

BankAccount account = new Account();
account.Deposit(500);  // true
account.Withdraw(1000);  // false, not enough money on the account
public class BankAccount 
{
private double balance = 0;
public double GetBalance() { return this.balance; }  
public bool Deposit(double amount) { return false; }  
public bool Withdraw(double amount) { return false; }  // << test this
}

首先,要执行此行为,我认为您在类中的撤回方法需要更改如下:

public class BankAccount 
{
...
public bool Withdraw(double amount) 
{ 
if ((balance - amount) < 0)
{
return false;
}
// withdraw procedure
} 
}

那么相应的测试可能如下所示:

[Fact]
public void BankAccount_Withdraw_ShouldPreventOverdraft()
{
var account = new BankAccount();    //Initializes balance to 0
Assert.False(account.Withdraw(1));
}

如果您想用存款进行测试。

[Fact]
public void BankAccount_Withdraw_ShouldPreventOverdraftAfterDeposit()
{
var account = new BankAccount();    //Initializes balance to 0
account.Deposit(1)
Assert.False(account.Withdraw(2));
}

作为测试的提示:一般准则是事先设置您想要的环境(银行账户的状态(,执行正在测试的操作(提款大于余额(,然后在测试操作后断言系统处于正确的状态(来自Withdraw(...)的响应是错误的(。

相关内容

最新更新