在 FakeItEasy 7.0 中配置严格的假强制事件订阅

问题描述

当我对事件处理程序订阅使用严格伪造时,这些报告在 FakeItEasy 7.0 中未配置。

  • 当 fake 是 strict 时,会抛出异常 - 'Call to unconfigured method of strict fake: IFoo.add_MyEvent(value: System.EventHandler)'。
  • 我可以取消对 A.CallTo 配置的注释。但是后来测试没有通过。使用 MustHaveHappened 而不是Doesnothing 会带来另一个例外——“预计会找到它一次或多次,但没有调用假对象”。
  • 当我删除严格配置并让配置注释时,测试通过。

我应该如何将假配置为严格,但同时处理事件?

var foo = A.Fake<IFoo>(c => c.Strict());
A.CallTo(foo).Where(call => call.Method.Name == "add_MyEvent").MustHaveHappened();
var bar = new Bar(foo);
foo.MyEvent += Raise.With(foo,new EventArgs());
Assert.That(bar.EventCalled,Is.True);

public interface IFoo
{
    event EventHandler MyEvent;
}

public class Bar
{
    public Bar(IFoo foo)
    {
        foo.MyEvent += (o,s) => { EventCalled= true;};
    }

    public bool EventCalled { get; private set; } = false;
}

解决方法

你可以这样做:

var foo = A.Fake<IFoo>(c => c.Strict());
EventHandler handler = null;
A.CallTo(foo).Where(call => call.Method.Name == "add_MyEvent")
    .Invokes((EventHandler value) => handler += value);
var bar = new Bar(foo);
handler?.Invoke(foo,EventArgs.Empty);
Assert.That(bar.EventCalled,Is.True);

请注意,当您手动处理事件订阅时,您不能再使用 Raise 来引发事件,而只能手动调用委托。


编辑:FakeItEasy 6.x 不需要此解决方法... 看起来 7.0 引入了一个意外的重大更改。我会研究一下。


EDIT2:实际上,突破性的变化是预料之中的,我只是忘记了。我提出的解决方法实际上描述了in the documentation