Search code examples
testingmockingfakeiteasy

How to use Fake It easy with indexed property?


I have a interface that has an indexed property that I need to mock.

public interface MultipleLines
{
    [DispId(201)]
    int Count
    {
        [MethodImpl(MethodImplOptions.InternalCall)]
        [DispId(201)]
        get;
    }

    [DispId(202)]
    SomeLine this[[In] int Index]
    {
        [MethodImpl(MethodImplOptions.InternalCall)]
        [DispId(202)]
        [return: MarshalAs(UnmanagedType.Interface)]
        get;
    }}

How can I give value to MultipleLines.Item[0/or any number ] with Fake It easy ? This is the test I tried to write:

    [Fact]
    public void Test1()
    {
        var myValue = new SomeLine();
        var mockedLines = A.Fake<MultipleLines>();
        A.CallTo(() => mockedLines.Item[1]).Returns(myValue);
    }

This simple call works perfectly:

var line= mockedLines.Item[1];

Solution

  • Your interface seems to be a COM interface, and I think your problem might come from that. COM interop is a bit weird.

    Try to use this syntax instead:

    A.CallTo(() => mockedLines.get_Item(1)).Returns(myValue);
    

    I think this trick isn't necessary with recent version of C#, but I might be mistaken. Out of curiosity, which version of C# are you using?