我正在尝试编写一个xunit测试来测试该函数撤回,如果成功,则该函数应返回true,否则返回false。
我可以写单元测试来测试是否输入了值!我该如何写,以便可以测试,如果我提取的资金多于存款,那么它将返回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
}
答案 0 :(得分:0)
首先,要执行此行为,我认为您的类中的withdraw方法需要进行如下更改:
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(...)
的响应为假)。