How to use Fake It easy with indexed property?

103 Views Asked by At

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];
2

There are 2 best solutions below

1
Thomas Levesque On BEST ANSWER

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?

2
Blair Conrad On

I think you've accessing the property incorrectly.

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

works for me.

That is, this test passes:

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

    mockedLines[1].Should().BeSameAs(myValue);
}