【问题标题】:How to mock a method that returns void but modifies the reference type passed in?如何模拟返回void但修改传入的引用类型的方法?
【发布时间】:2020-09-29 15:31:24
【问题描述】:

我有一个类似的界面 -

public interface ILedgerStoreRepository
{
    void AddInvoiceDetailsToBatchWriteObj(ref BatchWrite<InvoiceDetailsDAO> batchWriteDetails,
        ref InvoiceDetailsDAO invoiceDetails);
}

我想模拟这个函数,我只想验证 invoiceDetails 值作为我的验证。目前我正在尝试 -

    var repoMock = new Mock<ILedgerStoreRepository>();
    repoMock.Setup(m =>
        m.AddInvoiceDetailsToBatchWriteObj(ref batchWriteObj1,
            ref It.Ref<InvoiceDetailsDAO>.IsAny)).Callback<BatchWrite<InvoiceDetailsDAO>, InvoiceDetailsDAO>(
        (write, dao) =>
        {
            Assert.Equal(LedgerStoreTestConstants.TestInvoiceDetailsMappingDao, dao);
        }).Verifiable();

但它向我抛出了以下错误 -

System.ArgumentException 无效的回调。设置带参数的方法(参考 BatchWrite、参考 InvoiceDetailsDAO)无法调用带参数的回调(BatchWrite、InvoiceDetailsDAO)。

谁能帮我解决这个问题?

【问题讨论】:

  • 您需要使用自定义委托类型来实现这一点。检查这个link

标签: c# mocking


【解决方案1】:

我稍微修改了输入参数以便能够测试它。

public interface ILedgerStoreRepository
{
        void AddInvoiceDetailsToBatchWriteObj(ref List<string> batchWriteDetails, ref string invoiceDetails);
}

public class TestClass
{
    public void Execute(ILedgerStoreRepository repo)
    {
        List<string> a = new List<string> { "Test", "Alpha" };
        string b = "Alpha";
        repo.AddInvoiceDetailsToBatchWriteObj(ref a, ref b);
    }
}

// You need this delegate
delegate void AddInvoiceCallback(ref List<string> batchWriteDetails, ref string invoiceDetails);

[Test]
public void DummyTest()
{
    var repoMock = new Mock<ILedgerStoreRepository>();
    repoMock.Setup(m =>
                     m.AddInvoiceDetailsToBatchWriteObj(ref It.Ref<List<string>>.IsAny,
                                                              ref It.Ref<string>.IsAny))
                .Callback(new AddInvoiceCallback((ref List<string> batch, ref string details)
            =>
            {
                Assert.That(batch.Contains("Test"));
            })).Verifiable();

    // Act   
    new TestClass().Execute(repoMock.Object);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2014-11-04
    • 2017-06-29
    • 2012-03-24
    相关资源
    最近更新 更多