c# - 涉及 dbcontext 的 NUnit 单元测试
问题描述
我有下面的代码,现在可以测试了。问题是当它到达实体框架(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;
解决方案
推荐阅读
- python - 从 Bash 或 Python 获取 Google Chrome IndexedDB 中的数据
- javascript - 调用带有多个括号的函数
- scip - 我如何在 SCIP 的 python 版本中初始化我的预求解器
- onedrive - 为 Onedrive 调用“https://api.onedrive.com/v1.0/me/drive/sharedWithMe”时获取“无效的 API 或资源”
- android - Android:从路径创建投影
- java - 如何维护Socket连接?
- gradle - Gradle,如何强制选择第三方依赖项的最新版本
- r - Filter dataframe by values being subset of a given set
- python - 在 Python Flask 中维护会话数据
- javascript - 在 reactjs 中剪切图像