I'm getting an odd NullReferenceException that I can't understand when trying to mock up a collection to enumerate. I don't think it's anything caused by Mock but I'm not 100% sure. Can anyone identify anything silly that I'm doing?
InfoDataSet<OrderItemInfo> orders = OrderItemInfoProvider.GetOrderItems(orderInfo.OrderID);
foreach (OrderItemInfo orderItem in orders)
{
// Exception thrown on the first attempt to get an OrderItem in the foreach
}
The stack trace from this line of code is the following:
System.NullReferenceException: Object reference not set to an instance
of an object. Result StackTrace: at
CMS.SettingsProvider.ObjectDataSet1.GetEnumerator() at
1.GetObjectEnumerator() at
CMS.SettingsProvider.ObjectDataSet
CMS.SettingsProvider.InfoDataSet`1.d__0.MoveNext()
at ...
The content of the collection is simply a wrapper around an IEnumerable. In my case this should give you an idea on what is going on. GetEnumerator (both implicit and none implicit) implementations simply call through to values.
private IEnumerable<T> values;
/// <summary>
/// Initializes a new instance of the <see cref="MockDataSet{T}"/> class.
/// </summary>
/// <param name="values">The values.</param>
public MockDataSet(IEnumerable<T> values)
{
if (values == null)
throw new ArgumentNullException("values");
this.values = values;
}
Values has a single value in it, that I can enumerate fine via the watch window...
Can anyone explain what I'm doing wrong here?
It's a bit of an odd one this that I think is partially down to the CMS underneath (Kentico). I came across a problem earlier which I posted a question on Unable to call ToArray() on 3rd party class and I just realised this could be having the same affect.
It seems that the result of InfoDataSet<OrderItemInfo> orders = OrderItemInfoProvider.GetOrderItems(orderInfo.OrderID);
is difficult for the compiler to determine the type of. Therefore I think a cast is occuring underneath say
((IEnumerable<OrderItemInfo>)orders)
I believe this is failing, causing the IEnumerable to be null, and hence the NullReferenceException. The resolution is a simple cast of each item:
InfoDataSet<OrderItemInfo> orders = OrderItemInfoProvider.GetOrderItems(orderInfo.OrderID);
foreach (OrderItemInfo orderItem in orders.Cast<OrderItemInfo>())
{
// Now works
}