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

shu*_*iar 1 nunit unit-testing moq mocking 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());
}
Run Code Online (Sandbox Code Playgroud)

以下是正在测试的方法:

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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

通过调试我发现x => x.FileName返回null,但即使我将它与null比较,我仍然得到一个null而不是我要返回的Deal Summary.有任何想法吗?

MNG*_*inn 10

我猜你的设置与你打的电话不匹配,因为它们是两个不同的匿名lambda.你可能需要类似的东西

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

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

  • 谢谢,当我将代码更新为 `_mockRepository.Setup(r =&gt; r.Get(It.IsAny&lt;Expression&lt;Func&lt;DealSummary, bool&gt;&gt;&gt;())).Returns(new DealSummary { FileName = "Test" });` 测试通过。 (2认同)