I have these 3 methods for ATM mock program.
public decimal CheckBalance(BankAccount account)
{
return account.AccountBalance;
}
public void Deposit(BankAccount account, BankTransaction bankTransaction)
{
account.AccountBalance += bankTransaction.TransactionAmount;
}
public void Withdraw(BankAccount account, BankTransaction bankTransaction)
{
if(bankTransaction.TransactionAmount > account.AccountBalance)
{
throw new Exception("Withdraw failed. Transaction amount is more than account balance.");
}
account.AccountBalance -= bankTransaction.TransactionAmount;
}
And here are my xUnit unit test methods. The test data is in-memory for this version.
[Theory, MemberData(nameof(CheckBalanceShouldReturnValidBalanceAmount_Data))]
public void CheckBalanceShouldReturnValidBalanceAmount(BankAccount account, decimal accountBalance)
{
// Act
var balance = _atm.CheckBalance(account);
// Assert
Assert.Equal(accountBalance, balance);
}
[Theory, MemberData(nameof(DepositShouldPass_Data))]
public void DepositShouldPass(BankAccount account, BankTransaction bankTransaction, BankAccount accountExpected)
{
// Act
_atm.Deposit(account, bankTransaction);
var balance = _atm.CheckBalance(account);
// Assert
Assert.Equal(accountExpected.AccountBalance, balance);
}
[Theory, MemberData(nameof(WithdrawShouldPass_Data))]
public void WithdrawShouldPass(BankAccount account, BankTransaction bankTransaction, BankAccount accountExpected)
{
// Act
_atm.Withdraw(account, bankTransaction);
var balance = _atm.CheckBalance(account);
// Assert
Assert.Equal(accountExpected.AccountBalance, balance);
}
[Theory, MemberData(nameof(WithdrawAmountMoreThanBalanceShouldFail_Data))]
public void WithdrawAmountMoreThanBalanceShouldFail(BankAccount account, BankTransaction bankTransaction)
{
// Assert and Act
var exception = Assert.Throws<Exception>(() => _atm.Withdraw(account, bankTransaction));
Assert.Equal("Withdraw failed. Transaction amount is more than account balance.",
exception.Message);
}
All tests passed successfully. Any comments on coding style of unit test?
Edited After Answer with extra class:
namespace XUnitSample.ClassLib.Models
{
public class BankAccount
{
public int Id { get; set; }
public int BankAccountNo { get; set; }
public decimal AccountBalance { get; set; }
}
}
namespace XUnitSample.ClassLib.Models
{
public class BankTransaction
{
public int Id { get; set; }
public decimal TransactionAmount { get; set; }
public TransactionTypeEnum TransactionType { get; set; }
}
public enum TransactionTypeEnum
{
Deposit, Withdraw, ThirdPartyTransfer
}
}