I have a unit test to verify that an object (say Foo) will call certain method (say Bar) when an event is fired with certain eventArgs. To mock the said method, I use virtual and stub the Foo class
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
However, the above failed, Bar will not be called, apparently because the Foo object is not event constructed. However if I add a line like below:
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
It will work, because calling get on .Object apparently forces mock to construct the object. Is there a more elegant solution than adding this line ?
I don’t think you can. I checked out the moq source and poked through it and it doesn’t look like the proxy intercepter from castle is actually created until you call
.Object. Look at this trace:Followed by
Which does this:
ProxyFactory actually creates the object and wraps it in a proxy