Unfortunately, as mentioned in the article, you can't mock mscorlib types, which includes List<T>. That means either:
- You need to write a wrapper around the list and not access the list directly, OR
- You're not going to be able to return a known value for any arbitrary location in the list.
More directly, since it doesn't look like you're wrapping the list - you're accessing it directly - you're not going to be able to do what you want to do.
I suppose another alternative would be to create a dummy list of sufficiently large size such that any index in the range you could ask for will actually have a corresponding element in the dummy list and use the ObjectState mocking mechanism.
Which is to say:
[Test]
public void FieldListMocks()
{
// Figure out what the largest possible index
// is that your test will ask for. You won't be able
// to use Int32.MaxValue, though, because you'll run
// out of memory.
int largestPossibleIndex = 1000;
ListExample example = new ListExample();
ObjectState state = new ObjectState(example);
List<string> expectedList = new List<string>(largestPossibleIndex);
// Fill the dummy list with values. It'll actually
// have to have the value IN the list, though,
// because you can't mock List<T>.
for(int i = 0; i < largestPossibleIndex; i++)
{
expectedList.Add("expected");
}
// Do the mocking. We still have a restriction that
// publicIndex is less than largestPossibleIndex.
state.SetField("PublicList", expectedList);
int publicIndex = 10; //can be any number
Assert.AreEqual("expected", example.PublicList[0]);
Assert.AreEqual("expected", example.PublicList[publicIndex]);
// When we're done, we can reset things back to the
// original values, which means the real PublicList
// will be back - and will still be empty.
state.ResetState();
Assert.IsEmpty(example.PublicList);
}
I don't think I'd actually go down that route, though. Seems a little heavy-handed. Instead, I'd look at either wrapping the list or re-examining the test to see if I really need to test that a list returns a specific value for literally ANY index. Might be that the test can be changed such that it still tests the code but doesn't require you to mock every arbitrary index anyone could ask for.