Spoofing an array call for a specific index throws an exception
Having the following unit test:
public interface ITestMe
{
object[] Values { get; }
}
[Test]
public void Test ()
{
var sut = A.Fake<ITestMe> ();
A.CallTo (() => sut.Values[0]).Returns (4);
Assert.That (sut.Values[0], Is.EqualTo (4));
}
results in the following exception:
System.InvalidCastException : Unable to cast object of type 'System.Linq.Expressions.SimpleBinaryExpression' to type 'System.Linq.Expressions.InvocationExpression'.
at FakeItEasy.Expressions.CallExpressionParser.Parse(LambdaExpression callExpression)
at FakeItEasy.Configuration.FakeConfigurationManager.AssertThatMemberCanBeIntercepted(LambdaExpression callSpecification)
at FakeItEasy.Configuration.FakeConfigurationManager.CallTo(Expression1 callSpecification) at FakeItEasy.A.CallTo(Expression1 callSpecification)
Or maybe I don't know how to specify a fake for the indexer?
source to share
The problem occurs because it is Values
not an index. It is a property that returns an array.
Unconfigured Values
will return a zero-length array (since arrays are not forged). What's happening here and ()=>sut.Values[0]
will fail if it ever gets executed (which FakeItEasy doesn't).
So, the real benefit here is that since it Values
is an array that is not fake (see What can be faked? ) There is no way for FakeItEasy to fetch the return value for a specific offset. The best thing to do is return an Values
array of your choice, as @CharlesMager suggests. For example:
var myArray = new object[100];
myArray[0] = 4;
myArray[50] = 17;
A.CallTo(() => sut.Values).Returns(myArray);
source to share