调用它并将其用作存根或模拟是正确的吗?

时间:2014-10-30 08:57:10

标签: c# unit-testing tdd xunit.net

我使用手写假货作为演示应用,但我不确定我是否正确使用了模拟。这是我的代码:

[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);
        }
    }
}

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

1 个答案:

答案 0 :(得分:3)

这就是模拟框架的工作原理

  • 您要么对组件之间的交互进行假设(通常通过各种Expect - 家庭方法完成)以及稍后Verify他们(您的第二次测试)
  • 或者您告诉您的测试双以某种方式行事StubSetup),因为它在流程中是必要的(您的第一次测试)

这种方法是正确的,但它又重新发明了轮子。除非你有充分的理由这样做,否则我会花一些时间学习并使用一个模拟框架(MoqFakeItEasy)。

相关问题