首页 > 解决方案 > 涉及 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;

标签: c#nunit

解决方案


推荐阅读