Having trouble getting a Mocked method to return null

Viewed 65

I'm mocking a method using Moq and I want the method to return null but it's not returning null and I'm not sure why.

This is my setup code:

var mock2 = new Mock<ReminderRepository>(stubPatientRemindersDBModelContainer);
mock2.CallBase = true;
mock2.Setup(x => x.GetPatientEscalations(userName, patientId, startDateTime, endDateTime, new DataTable()))
    .Returns((PatientEscalationsDto)null);

When debugging, I was hoping that the variable assigned to GetPatientEscalations would be null but it isn't.

What am I doing wrong?

1 Answers

Check the arguments being passed into the mock setup.

 mock2
    .Setup(x => x.GetPatientEscalations(userName, patientId, startDateTime, endDateTime, new DataTable()))
    .Returns((PatientEscalationsDto)null);

if they do not match what is actually passed in when invoking the member it will revert back to the base call as you have CallBase enabled.

Try loosening the expectation of the mocked member using the It.IsAny<T>() argument matchers

 mock2
    .Setup(x => x.GetPatientEscalations(
        It.IsAny<string>(), 
        It.IsAny<int>(), //this is an assumption. use desired type here
        It.IsAny<DateTime>(), 
        It.IsAny<DateTime>(), 
        It.IsAny<DataTable>()))
    .Returns((PatientEscalationsDto)null);

That way any arguments passed will match and invoke the mocked members to behave as expected.

Related