Fake class which inherits from multiple interfaces

140 Views Asked by At

How do you fake a class with FakeItEasy that implements multiple interfaces.

e.g. A class that implements both IFoo and IBar

I've tried the following but it doesn't work

A.Fake<IFoo>(builder => builder.Implements<IBar>());
1

There are 1 best solutions below

0
Renat On

Well, it actually works, if do type casting. A.Fake<IFoo>(...) returns IFoo, and FakeItEasy simply knows nothing about any aggregate type/interface which would implement both IFoo and IBar, hence manual type casting to IBar is required.

public static void Main()
{
    var o = A.Fake<IFoo>(builder => builder.Implements<IBar>());
    
    A.CallTo(() => o.A())
         .Invokes(() => Console.WriteLine("I'm IFoo.A()"));
    A.CallTo(() => ((IBar)o).B())
         .Invokes(() => Console.WriteLine("I'm IBar.B()"));

    o.A();
    var oAsBar = (IBar)o;
    oAsBar.B();
}

public interface IFoo
{
    void A();
}
public interface IBar
{
    void B();
}

produces

I'm IFoo.A()
I'm IBar.B()