我有下面的代码,现在可以测试了。问题在于,当到达与实体框架(EF)相关的代码时,它就挂在那里(无限循环)。我认为我的临时解决方案是注释掉与EF相关的代码。
我知道要测试EF,可能需要MOQ或集成测试之类的东西,我计划稍后再进行测试。同时,如何“拆分”所有这些EF代码,以便可以对其他可测试代码执行NUnit测试?这是我拥有的一种方法:
public void PlaceDeposit(BankAccount account, decimal _transaction_amt)
{
if (_transaction_amt <= 0)
_msgPrinter.PrintMessage("Amount needs to be more than zero. Try again.", false);
else if (_transaction_amt % 10 != 0)
_msgPrinter.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false);
else if (!PreviewBankNotesCount(_transaction_amt))
_msgPrinter.PrintMessage($"You have cancelled your action.", false);
else
{
var transaction = new Transaction()
{
AccountID = account.Id,
BankAccountNoTo = account.AccountNumber,
TransactionType = TransactionType.Deposit,
TransactionAmount = _transaction_amt,
TransactionDate = DateTime.Now
};
repoTransaction.InsertTransaction(transaction);
// Add transaction record - End
account.Balance = account.Balance + _transaction_amt;
ctx.SaveChanges();
_msgPrinter.PrintMessage($"You have successfully deposited {Utility.FormatAmount(_transaction_amt)}", true);
}
}
我在NUnit中有此测试方法,可以很好地工作:
[TestCase("Amount needs to be more than zero. Try again.",0)]
[TestCase("Amount needs to be more than zero. Try again.",-1)]
[TestCase("Key in the deposit amount only with multiply of 10. Try again.", 1)]
[TestCase("Key in the deposit amount only with multiply of 10. Try again.", 5)]
public void ShowErrorMessage_OnPlaceDeposit(string expectedMessage, decimal transactionAmount)
{
// Arrange - Start
var mock = new MockMessagePrinter();
MeybankATM atmCustomer = new MeybankATM(new RepoBankAccount(), new RepoTransaction(), mock);
BankAccount bankAccount = new BankAccount()
{
FullName = "John",
AccountNumber = 333111,
CardNumber = 123,
PinCode = 111111,
Balance = 2000.00m,
isLocked = false
};
// Arrange - End
// Act
atmCustomer.PlaceDeposit(bankAccount, transactionAmount);
// Assert
Assert.AreEqual(expectedMessage, mock.Message);
}
现在,我所剩下的只是测试余额更新部分:
account.Balance = account.Balance + _transaction_amt;