I want to mock a Linq expression that returns a Dictionary<string, string>
Dictionary<string, string> properties = new Dictionary<string, string>()
{
{ "Service", "serviceTest" }
}
equipment.SetProperties(dmsElement.Properties.ToDictionary(x => x.Definition.Name, x => x.Value));
Here is the unit test
fakeEquipment.Setup(e => e.Properties.ToDictionary(It.IsAny<Func<IDmsElementProperty, string>>(), It.IsAny<Func<IDmsElementProperty, string>>())).Returns(properties);
I am getting the following error:
System.NotSupportedException: 'Unsupported expression: ... => ....ToDictionary<IDmsElementProperty, string, string>(It.IsAny<Func<IDmsElementProperty, string>>(), It.IsAny<Func<IDmsElementProperty, string>>())
How can I setup the ToDictionary method to retrieve the expected values?
CodePudding user response:
You cannot mock the ToDictionary
method because it is an extension method found in the System.Enumerable
type. That method is going to enumerate your .Properties
property no matter what.
You can and should, however, mock directly e.Properties
.
You can return an implementation of the IPropertyCollection
interface, or if it's not that much of a problem write a very simple adapter exposing an underlying collection (be it a dictionary or a list).
If you have access to an existing class (say, ListPropertyCollection<T>
), you could just instantiate it.