3

使用带两个接口的MoqOuterInner,我无法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's 事件?似乎没有什么可以解雇他们。

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

Outer
  InnerPropChanged
4

1 回答 1

1

也许是表达式的错误或缺少的功能

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

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

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
于 2013-01-17T20:22:31.880 回答