FakeItEasy - Having an interface fake inherit from abstract while both share same interface inheritance

筅森魡賤 提交于 2019-12-12 15:11:19

问题


I have an interface

public interface IInterface { void DoSomething(); }

Another interface

public interface IOtherInterface : IInterface { }

An abstract class

public abstract class AbstractClass : IInterface
{
    public void DoSomething()
    {
        Console.WriteLine("Got here");
    }
}

I'm writing a unit test and fake IOtherInterface. The abstract class already contains helpful methods I'd want to leverage for my unit test. How would I make my A.Fake<IOtherInterface>(); inherit from AbstractClass?

This is what I've tried so far but it doesn't work - AbstractClass.DoSomething does not get hit.

        IOtherInterface fake = A.Fake<IOtherInterface>(builder => builder.Implements(typeof (AbstractClass)));

        fake.DoSomething();

Of course if I make a proxy like:

        var abstractFake = A.Fake<AbstractClass>();
        A.CallTo(() => fake.DoSomething()).Invokes(abstractFake.DoSomething);

        fake.DoSomething();

... things work as I wanted. Is there a built in mechanism to achieve this so that I don't need that proxy abstractFake object?

UPDATE

I need IOtherInterface because I have a client class that needs that IOtherInterface as dependency:

class Consumer
{
    public Consumer(IOtherInterface otherInterface)
    {
        otherInterface.DoSomething();
    }
}

回答1:


var fake = (IOtherInterface) A.Fake<AbstractClass>(builder =>
                               builder.Implements(typeof(IOtherInterface)));
A.CallTo(() => fake.DoSomething()).CallsBaseMethod();
fake.DoSomething();

Implements is intended to work only with interfaces, so the proper way to use it is to fake an interface or class and use Implements to add additional interface. I think it should've complained at you, so I raised complain when IFakeOptionsBuilder.Implements is passed a non-interface, which was fixed in FakeItEasy 2.0.0.

The CallsBaseMethod will ensure that the Abstract class's method is executed.

I would've recommended builder.CallsBaseMethods(), but this fails to redirect the call. I think it's because it's redirecting AbstractClass.DoSomething, but when we cast the fake to IOtherInterface and call DoSomething, it's not matching. I've raised investigate interaction between Implements and CallsBaseMethods.



来源:https://stackoverflow.com/questions/28697918/fakeiteasy-having-an-interface-fake-inherit-from-abstract-while-both-share-sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!