调用并将其用作存根或mock是否正确

本文关键字:mock 是否 存根 调用 | 更新日期: 2023-09-27 18:28:20

我正在为演示应用程序使用手写的fakes,但我不确定我是否正确使用了mock。下面是我的代码:

[Fact]
    public void TransferFund_WithInsufficientAccountBalance_ThrowsException()
    {
        IBankAccountRepository stubRepository = new FakeBankAccountRepository();
        var service = new BankAccountService(stubRepository);
        const int senderAccountNo = 1, receiverAccountNo = 2;
        const decimal amountToTransfer = 400;
        Assert.Throws<Exception>(() => service.TransferFund(senderAccountNo, receiverAccountNo, amountToTransfer));
    }
    [Fact]
    public void TransferFund_WithSufficientAccountBalance_UpdatesAccounts()
    {
        var mockRepository = new FakeBankAccountRepository();
        var service = new BankAccountService(mockRepository);
        const int senderAccountNo = 1, receiverAccountNo = 2;
        const decimal amountToTransfer = 100;
        service.TransferFund(senderAccountNo, receiverAccountNo, amountToTransfer);
        mockRepository.Verify();
    }

双重测试:

public class FakeBankAccountRepository : IBankAccountRepository
{
    private List<BankAccount> _list = new List<BankAccount>
    {
        new BankAccount(1, 200),
        new BankAccount(2, 400)
    };
    private int _updateCalled;
    public void Update(BankAccount bankAccount)
    {
        var account = _list.First(a => a.AccountNo == bankAccount.AccountNo);
        account.Balance = bankAccount.Balance;
        _updateCalled++;
    }
    public void Add(BankAccount bankAccount)
    {
        if (_list.FirstOrDefault(a => a.AccountNo == bankAccount.AccountNo) != null)
            throw new Exception("Account exist");
        _list.Add(bankAccount);
    }
    public BankAccount Find(int accountNo)
    {
        return _list.FirstOrDefault(a => a.AccountNo == accountNo);
    }
    public void Verify()
    {
        if (_updateCalled != 2)
        {
            throw new Xunit.Sdk.AssertException("Update called: " + _updateCalled);
        }
    }
}

第二个测试实例化fake并将其引用为mock,然后调用verify方法。这种做法是对还是错?

调用并将其用作存根或mock是否正确

这就是模拟框架在中的工作方式

  • 您可以对组件之间的交互进行假设(通常通过各种Expect-族方法进行),然后对它们进行Verify-(第二次测试)
  • 或者你告诉你的测试替身以某种方式表现StubSetup),因为这在流程中是必要的(你的第一个测试)

这种方法是正确的,但它正在重新发明轮子。除非你有充分的理由这样做,否则我会投入一些时间学习和使用其中一种嘲讽框架(脑海中会浮现Moq或FakeItEasy)。