【问题标题】:Moq SetUp.Return not working for repository mockMoq SetUp.Return 不适用于存储库模拟
【发布时间】:2011-08-18 14:26:28
【问题描述】:

我试图模拟我的存储库的 Get() 方法以返回一个对象,以伪造对该对象的更新,但我的设置不起作用:

这是我的测试:

[Test]
public void TestUploadDealSummaryReportUploadedExistingUpdatesSuccessfully()
{
    var dealSummary = new DealSummary {FileName = "Test"};
    _mockRepository.Setup(r => r.Get(x => x.FileName == dealSummary.FileName))
        .Returns(new DealSummary {FileName = "Test"}); //not working for some reason...

    var reportUploader = new ReportUploader(_mockUnitOfWork.Object, _mockRepository.Object);
    reportUploader.UploadDealSummaryReport(dealSummary, "", "");

    _mockRepository.Verify(r => r.Update(dealSummary));
    _mockUnitOfWork.Verify(uow => uow.Save());
}

这是正在测试的方法:

public void UploadDealSummaryReport(DealSummary dealSummary, string uploadedBy, string comments)
{
    dealSummary.UploadedBy = uploadedBy;
    dealSummary.Comments = comments;

    // method should be mocked to return a deal summary but returns null
    var existingDealSummary = _repository.Get(x => x.FileName == dealSummary.FileName);
    if (existingDealSummary == null)
        _repository.Insert(dealSummary);
    else
        _repository.Update(dealSummary);

    _unitOfWork.Save();
}

这是我在运行单元测试时遇到的错误:

Moq.MockException : 对模拟的预期调用至少一次,但从未执行:r => r.Update(.dealSummary) 未配置任何设置。

执行的调用: IRepository1.Get(x => (x.FileName == value(FRSDashboard.Lib.Concrete.ReportUploader+<>c__DisplayClass0).dealSummary.FileName)) IRepository1.Insert(FRSDashboard.Data.Entities.DealSummary) 在 Moq.Mock.ThrowVerifyException(MethodCall 预期,IEnumerable1 setups, IEnumerable1 actualCalls,Expression 表达式,Times 次,Int32 callCount) 在 Moq.Mock.VerifyCalls(Interceptor targetInterceptor,MethodCall 预期,Expression 表达式,Times 次) 在 Moq.Mock.Verify(模拟模拟,Expression1 expression, Times times, String failMessage) at Moq.Mock1.Verify(Expression`1 表达式) 在 FRSDashboard.Test.FRSDashboard.Lib.ReportUploaderTest.TestUploadDealSummaryReportUploadedExistingUpdatesSuccessfully

通过调试,我发现 x => x.FileName 返回 null,但即使我将其与 null 进行比较,我仍然得到 null 而不是我想要返回的交易摘要。有什么想法吗?

【问题讨论】:

    标签: unit-testing mocking nunit moq repository-pattern


    【解决方案1】:

    我猜您的设置与您拨打的电话不匹配,因为它们是两个不同的匿名 lambda。你可能需要像

    _mockRepository.Setup(r => r.Get(It.IsAny<**whatever your get lambda is defined as**>()).Returns(new DealSummary {FileName = "Test"});
    

    您可以通过在存储库的 Get() 方法中设置断点并查看它是否被命中来进行验证。不应该。

    【讨论】:

    • 谢谢,当我将代码更新为_mockRepository.Setup(r =&gt; r.Get(It.IsAny&lt;Expression&lt;Func&lt;DealSummary, bool&gt;&gt;&gt;())).Returns(new DealSummary { FileName = "Test" }); 时,测试通过了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2011-05-27
    • 2011-05-27
    • 1970-01-01
    • 2011-10-26
    相关资源
    最近更新 更多