被嘲笑的内在对象事件不会触发?



使用Moq有两个接口,OuterInner,我无法让Outer.Inner.SomeEvent开火。

public interface Outer
{
    Inner Inner { get; }
}
public interface Inner
{
    int Prop { get; set; }
    event EventHandler PropChanged;
}
public void Test()
{
    Mock<Outer> omock = new Mock<Outer>();
    Mock<Inner> imock = new Mock<Inner>();
    Console.WriteLine("Inner");
    imock.Object.PropChanged += InnerPropChanged;
    imock.Raise(m => m.PropChanged += null, EventArgs.Empty);
    imock.Object.PropChanged -= InnerPropChanged;
    // This has no effect.
    //omock.Setup(m => m.Inner).Returns(imock.Object);
    Console.WriteLine("Outer");
    // Both the auto recursive and the explicit above produce the same behavior.
    omock.SetupProperty(m => m.Inner.Prop, -1);
    omock.Object.Inner.PropChanged += InnerPropChanged;
    omock.Raise(m => m.Inner.PropChanged += null, EventArgs.Empty);
}
public void InnerPropChanged(object sender, EventArgs e)
{
    Console.WriteLine("  InnerPropChanged");
}

调用Test()时的输出:

Inner
  InnerPropChanged
Outer

如何提醒订阅者注意Inner的任何事件?似乎没有什么能解雇他们。

编辑-为了澄清,我希望能够从Outer上下文中引发Inner事件,因此最终输出应包括:

Outer
  InnerPropChanged

可能是错误或缺少的功能,表达式

omock.Raise(m => m.Inner.PropChanged += null, EventArgs.Empty);

不工作…但是,您可以使用Mock.Get获得生成的Inner模拟,然后您可以在其上引发事件:

public void Test()
{
    Mock<Outer> omock = new Mock<Outer>();
    Console.WriteLine("Outer");
    omock.SetupProperty(m => m.Inner.Prop, -1);
    omock.Object.Inner.PropChanged += InnerPropChanged;
    Mock.Get(omock.Object.Inner)
        .Raise(m => m.PropChanged += null, EventArgs.Empty);
}

产生你想要的输出:

Outer
  InnerPropChanged

相关内容

  • 没有找到相关文章

最新更新