Reputation: 38663
This query does not working while giving dummy data via Moq Setup.
colorsList.Select(cl => (string)cl.MainTypeCode).Where(mt => mt != null).Distinct().ToList()
Passing data by Using Moq:
mockColorsRepository.Setup(rep => rep.GetColorsList()).Returns(Task.FromResult<IEnumerable<dynamic>>
(new[] { new { DoorCode = "001", MainTypeCode = "1" }, new { DoorCode = "002", MainTypeCode = "2" } }));
Where GetColorsList()
has an async method and dynamic return type
Task<IEnumerable<dynamic>> GetColorsList();
Passing data by hardcoding:
But it is working while I am hardcoding same way of data without using Moq, like
var colorsList = Task.FromResult<IEnumerable<dynamic>>(new[] { new { DoorCode = "001", MainTypeCode = "1" },
new { DoorCode = "002", MainTypeCode = "2" } }).Result;
The problem is: you can see the data in both way while of debugging, But the Lambda query does not working while passing Mock data via Moq Setup.
Note Does not working means it's throwing an
Object
does not contains a definition formaintypecode
error.
Upvotes: 1
Views: 464
Reputation: 38663
Thanks @DaveParsons to gave me a key idea.
I think anonymous types are internal by default hence you aren't able to access the properties from another library, namely your test project
I got it from this discussion : Return/consume dynamic anonymous type across assembly boundaries
So I am go to useExpandoObject
for mocking data
public static IEnumerable<dynamic> GetValues()
{
List<ExpandoObject> expando = new List<ExpandoObject>();
dynamic expandoObject = new ExpandoObject();
expandoObject.DoorCode = "123";
expandoObject.MainTypeCode = "123";
expando.Add(expandoObject);
dynamic expandoObject1 = new ExpandoObject();
expandoObject1.DoorCode = "321";
expandoObject1.MainTypeCode = "321";
expando.Add(expandoObject1);
return expando;
}
I am passing that mock data to the return method of Moq setup
like
mockColorsRepository.Setup(rep => rep.GetColorsList()).Returns(Task.FromResult(GetValues()));
Everything is working now.
Upvotes: 1
Reputation:
Your mock is returning an IEnumerable<f__AnonymousType0<string,string>>
which is generated by the compiler as an internal
class and so you don't have access to the properties from your test library.
Ideally you would be able to rewrite so as to replace your use of dynamic
with a class that you define and have control over (and can therefore access appropriately).
Another option would be to use reflection to get the values from the object something along the lines of cl.GetType().GetProperty("MainTypeCode").GetValue(cl)
this is, in my opinion, a bit of a hacky solution but it's an option nonetheless.
Upvotes: 2