jeudi 4 février 2016

How do you mock IEnumerable

I have been having issues implementing the correct technique to mock out the Linq methods for an IEnumerable.

{
    var qs = Substitute.For<IEnumerable<object>>();
    qs.ElementAt(i).Returns(q);
    qs.Count().Returns(i);
}

Which is meant to test a method, which contains both pulling an item out of the list at random or in a controlled fashion.

private IEnumerable<T> list;
async object Save(object obj, byte i = 0)
{
     var random = new Random();
     var index = i == 0 ? random.Next(0, list.Count()) : i;
     return list.ElementAt(index);
}

Doing this results in:

at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at System.Linq.Enumerable.ElementAt[TSource](IEnumerable`1 source, Int32 index)
   at King.Azure.Unit.Test.Data.StorageQueueShardsTests.<Save>d__11.MoveNext() in C:\Users\jefkin\Documents\GitHub\King.Azure\King.Azure.Unit.Test\Data\StorageQueueShardsTests.cs:line 127
--- End of stack trace from previous location where exception was thrown ---
   at NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object invocationResult)
   at NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext context)
Result Message: 
System.ArgumentOutOfRangeException : Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Aucun commentaire:

Enregistrer un commentaire