【问题标题】:FakeItEasy - Having an interface fake inherit from abstract while both share same interface inheritanceFakeItEasy - 有一个假接口继承自抽象,而两者共享相同的接口继承
【发布时间】:2016-05-31 03:41:43
【问题描述】:

我有一个界面

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();

...事情如我所愿。是否有内置机制来实现这一点,这样我就不需要代理 abstractFake 对象?

更新

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

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

【问题讨论】:

  • 确实如此,但是abstractFake 变量的类型将是AbstractClass 而不是IOtherInterface。我需要IOtherInterface。查看更新:)
  • 感谢您提出这个问题。从 Blair Conrad 的回答中可以看出,结果提出了两个项目问题,这很棒!
  • @AdamRalph 老实说,看到 Blair 的专业活动通过创建那些您通常看不到的项目问题让我大吃一惊。通常,即使是项目的合作者也会说“去提交一个错误”之类的。无论如何,我很高兴我间接贡献了:)
  • 确实,Blair Conrad 对任何项目来说都是一笔巨大的财富!

标签: c# unit-testing mocking fakeiteasy


【解决方案1】:
var fake = (IOtherInterface) A.Fake<AbstractClass>(builder =>
                               builder.Implements(typeof(IOtherInterface)));
A.CallTo(() => fake.DoSomething()).CallsBaseMethod();
fake.DoSomething();

Implements 仅适用于接口,因此使用它的正确方法是伪造接口或类并使用Implements 添加额外的接口。我认为它应该向你抱怨,所以我提出了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

【讨论】:

  • 感谢@blairconrad 的帮助,感谢您主动提出投诉/调查。我不知道 FakeItEasy 的发布周期,但我期待这些问题得到解决。 :)
  • @JoaoMilasch,FakeItEasy 通常releases frequently,但与许多开源项目一样,时间表取决于核心团队的可用性和社区的贡献率。我不一定会期望快速 得到解决,因为核心团队参与了即将发布的 2.0 版本,而且这些问题都非常小。一种是有效地“添加警告消息,让用户知道他们使用了错误的实现”,另一种是非常极端的情况 - 两个非次要功能之间的交互,它有一个解决方法。
  • 很公平。无论如何,我对周围的工作感到满意。感谢您的帮助。
猜你喜欢
  • 2015-10-16
  • 2021-12-29
  • 2020-12-09
  • 2013-01-09
  • 2021-09-12
  • 2011-11-03
  • 2011-01-01
  • 1970-01-01
  • 2014-03-11
相关资源
最近更新 更多