我有一个单元测试来验证当使用某些 eventArgs 触发事件时对象(例如Foo
)将调用某些方法(例如)。Bar
为了模拟上述方法,我使用虚拟和存根Foo
类
Mock<Foo> stubbedFoo = new Mock<Foo>(mockEventProvider);
mockEventProvider.Raise( x => x.MyEvent += null, myEventArgs ) //fire the event
stubbedFoo.Verify(foo => foo.Bar()); verify Bar is called as a result
但是,上面失败了,Bar 不会被调用,显然是因为 Foo 对象不是事件构造的。但是,如果我添加如下一行:
Mock<Foo> stubbedFoo = new Mock<Foo>(mockEventProvider);
var workAround = stubbedFoo.Object //adding this workaround will work
mockEventProvider.Raise( x => x.MyEvent += null, myEventArgs ) //fire the event
stubbedFoo.Verify(foo => foo.Bar()); verify Bar is called as a result
它会起作用,因为在 .Object 上调用 get 显然会强制 mock 构造对象。有没有比添加这条线更优雅的解决方案?