Moq SetUp.Return不适用于存储库模拟

时间:2011-08-18 14:26:29

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

我正在尝试模拟我的存储库的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)   没有配置设置。

     

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

通过调试我发现 x =&gt; x.FileName 返回null,但即使我将它与null进行比较,我仍然得到一个null而不是我要返回的Deal Summary。有什么想法吗?

1 个答案:

答案 0 :(得分:9)

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

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

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