AlexB
AlexB

Reputation: 4536

Setup with ReturnsAsync, need to return passed in value but getting null

I need to mock my IVehicleRecordsRepository for some tests. So here's the repo interface:

public interface IVehicleRecordsRepository
{
    Task<VehicleRecord> StoreAsync(VehicleRecord veh, Guid? userId = null);
    //...
}

and now I try to mock it in the xUnit test so StoreMethod() should return the same value that was passed in as a parameter. Here's the test that tests this scenario:

[Fact]
public async Task ShouldGetValueFromMockedMethod()
{
    var mockRepo = new Mock<IVehicleRecordsRepository>();
    mockRepo
        .Setup(repo => repo.StoreAsync(It.IsAny<VehicleRecord>(), Guid.NewGuid()))
        .ReturnsAsync((VehicleRecord veh, Guid userId) => veh)
        // tried this too -> .Returns((VehicleRecord veh, Guid userId) => Task.FromResult(veh))
        ;

    VehicleRecord vr = new VehicleRecord(newVehicle, Guid.NewGuid());
    var testVeh = await mockRepo.Object.StoreAsync(vr);
    Assert.NotNull(testVeh); // ====> FAILS HERE
    Assert.AreEqual(vr, testVeh);
}

So, how can I get the same value I passed into StoreAsync() in return ?

Moq version: 4.7.99.0

Upvotes: 1

Views: 1796

Answers (1)

Gregg L
Gregg L

Reputation: 380

I've not used Moq, so forgive my ignorance.
In your act statement:

var testVeh = await mockRepo.Object.StoreAsync(vr);

you're only passing in the Vehicle Record ('vr'), but your mocked object is set up to also expect a Guid.NewGuid(), correct?

mockRepo.Setup(repo => repo.StoreAsync(It.IsAny<VehicleRecord>(), Guid.NewGuid()))

Could it be that it's not matching the expectation and therefore, never calls the "(mockObject.)ReturnsAsync" method?

Have you tried doing something like:

var guid = Guid.NewGuid;
VehicleRecord vr = new VehicleRecord(newVehicle, guid);
var testVeh = await mockRepo.Object.StoreAsync(vr, guid);

Or, perhaps simplifying it a bit, change your mockObject to not expect a Guid, since you're passing in only the VehicleRecord:

mockRepo.Setup(repo => repo.StoreAsync(It.IsAny<VehicleRecord>()))

Upvotes: 1

Related Questions