编程语言
首页 > 编程语言> > c#-FakeItEasy-伪造的接口继承自抽象,而两者共享相同的接口继承

c#-FakeItEasy-伪造的接口继承自抽象,而两者共享相同的接口继承

作者:互联网

我有一个界面

public interface IInterface { void DoSomething(); }

另一个界面

public interface IOtherInterface : IInterface { }

抽象类

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

我正在编写单元测试和伪造的IOtherInterface.抽象类已经包含了一些我想在单元测试中利用的有用方法.我如何制作A.Fake< IOtherInterface>();从AbstractClass继承?

到目前为止,这是我尝试过的方法,但是它不起作用-AbstractClass.DoSomething不会受到攻击.

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

        fake.DoSomething();

当然,如果我做一个代理,如:

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

        fake.DoSomething();

……事情如我所愿.是否有内置机制可以实现此目的,所以我不需要该proxy abstractFake对象?

更新

我需要IOtherInterface,因为我有一个需要将该IOtherInterface作为依赖项的客户端类:

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

解决方法:

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

实施工具仅旨在与接口一起使用,因此使用它的正确方法是伪造接口或类,并使用实施工具添加其他接口.我认为应该向您抱怨,所以我筹集了complain when IFakeOptionsBuilder.Implements is passed a non-interface,已在FakeItEasy 2.0.0中修复.

CallsBaseMethod将确保执行Abstract类的方法.

我会推荐builder.CallsBaseMethods(),但这无法重定向该调用.我认为这是因为它正在重定向AbstractClass.DoSomething,但是当我们将伪造的对象转换为IOtherInterface并调用DoSomething时,它是不匹配的.我已经筹集了investigate interaction between Implements and CallsBaseMethods.

标签:fakeiteasy,unit-testing,mocking,c
来源: https://codeday.me/bug/20191120/2045853.html