I got a problem with Moq and Automapper regarding IDataReader.
I found an example on stackoverflow and modified the code.
public static IDataReader MockIDataReader<T>(List<T> ojectsToEmulate) where T : class
{
var moq = new Mock<IDataReader>();
// This var stores current position in 'ojectsToEmulate' list
var count = 0;
moq.Setup(x => x.Read())
// Return 'True' while list still has an item
.Returns(() => count < ojectsToEmulate.Count)
// Go to next position
.Callback(() => count++);
var properties = typeof (T).GetProperties();
foreach (PropertyInfo t in properties)
{
var propName = t.Name;
moq.Setup(x => x[propName]).Returns(() => ojectsToEmulate[count].GetType().GetProperty(propName).GetValue(ojectsToEmulate[count],null));
}
return moq.Object;
}
}
My mapping:
Mapper.Configuration.CreateMap(typeof(IDataReader), typeof(IEnumerable<T>));
var result = Mapper.Map<IDataReader, IEnumerable<T>>(reader);
The problem I got here is that my result has 1 result a cityModel but all it’s properties are null. If I check the value from my mocked reader like reader[“name”] I got the “Alingsås” value so the mocking is correct but Automapper seams to have the problem.
I use a List of objects that I pass to my method that mocks it all.
var cityModel = new CityModel();
cityModel.Name = "Alingsås";
cityModel.Id = "SE";
cityModel.CountryId = "SE";
var cityModels = new List<CityModel>();
cityModels.Add(cityModel);
_fakeReader = MockTester.MockIDataReader(cityModels);
The code works fine, no exception is thrown, but the mapper gives me an object without the
valules. I can see in the debugger my reflection code works but it seams like my
x[“Name”] aren’t the method Automapper call from IDataReader? Or is it?
What can be wrong here?
Automapper internally uses the int indexer of
IDataReaderso you need to callSetupon that instead ofItem[String].Checking the Automapper’s source you need to setup some additional methods to make it work: