shuniar
shuniar

Reputation: 2622

Moq SetUp.Return not working for repository mock

I am trying to mock my repository's Get() method to return an object in order to fake an update on that object, but my setup is not working:

Here is my Test:

[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());
}

Here is the method that is being tested:

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();
}

And here is the error that I get when I run my unit test:

Moq.MockException : Expected invocation on the mock at least once, but was never performed: r => r.Update(.dealSummary) No setups configured.

Performed invocations: IRepository1.Get(x => (x.FileName == value(FRSDashboard.Lib.Concrete.ReportUploader+<>c__DisplayClass0).dealSummary.FileName)) IRepository1.Insert(FRSDashboard.Data.Entities.DealSummary) at Moq.Mock.ThrowVerifyException(MethodCall expected, IEnumerable1 setups, IEnumerable1 actualCalls, Expression expression, Times times, Int32 callCount) at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times) at Moq.Mock.Verify(Mock mock, Expression1 expression, Times times, String failMessage) at Moq.Mock1.Verify(Expression`1 expression) at FRSDashboard.Test.FRSDashboard.Lib.ReportUploaderTest.TestUploadDealSummaryReportUploadedExistingUpdatesSuccessfully

Through debugging I have found that the x => x.FileName is returning null, but even if i compare it to null I still get a null instead of the Deal Summary I want returned. Any ideas?

Upvotes: 3

Views: 11116

Answers (1)

MNGwinn
MNGwinn

Reputation: 2394

I'm guessing your setup isn't matching the call you make because they're two different anonymous lambdas. You may needs something like

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

You could verify by setting a breakpoint in the Get() method of your repository and seeing if it is hit. It shouldn't be.

Upvotes: 14

Related Questions