这样叫做存根或模拟在IT技术中是否正确使用?

3

我正在使用手写的假数据来演示一个应用程序,但我不确定我是否正确地使用了模拟数据。以下是我的代码:

[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个回答

3

以下是模拟框架的工作原理

  • 您可以通过各种Expect系列方法来做出关于组件之间交互的假设,并在稍后使用Verify来验证它们(即第二个测试)。
  • 或者您可以告诉您的测试替身以某种方式行为(例如StubSetup),因为在流程中这是必要的(即您的第一个测试)。

这种方法是正确的,但却是重复发明轮子。除非您有非常充分的理由这样做,否则我建议您花些时间学习和使用其中一个模拟框架(例如MoqFakeItEasy)。


@peter 如果你对存根和模拟之间的区别感兴趣,从经典意义上讲,你有一个模拟。具有讽刺意味的是,大多数模拟框架(我知道 Moq 特别如此)都帮助创建存根,即使它们称之为模拟。请参见 http://martinfowler.com/articles/mocksArentStubs.html 以了解这两个术语之间的详细对比。 - Keith Payne
我知道它们之间的区别。我可以轻松地使用框架创建它们。 - peter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接