Question

I'm currently using NSubstitute as my mocking framework and over I'm doing reasonably well, with one exception that is...

I'm attempting to mock an interaction that calls an event from inside my mocked object, unfortunately I'm really struggling to do this. The setup is something like this...

Public Interface IMockObject
    Event MyMockedEvent( someId as Integer )
    Sub MyRoutineThatInvokesMyMockedEvent( someId as Integer)
End Interface

...so in my Unit Test I need to mock the 'MyRoutineThatInvokesMyMockedEvent' to receive the ID and then raise the 'MyMockedEvent'. So far I have come up with...

Dim mockedObject = Substitute.For(Of IMockObject)()
mockedObject.When(
    Sub(x) x.MyRoutineThatInvokesMyMockedEvent( 999 )).Do( 
        Sub(y) 'RaiseTheEventHere )

...but I'm stuck on actually raising the event with the following not valid...

mockedObject.When(
    Sub(x) x.MyRoutineThatInvokesMyMockedEvent( 999 )).Do( 
        Sub(y) RaiseEvent MyMockedEvent(999) )

...I do have a theory that this may not be possible in VB.NET (without creating a helper routine) but will gladly appreciate any help on how to achieve the above without the helper routine.

Was it helpful?

Solution

OK, found the answer. Or something like it.

The problem I believe is due to the event definition that is used - by reconfiguring the 'MyMockedEvent' to use its own 'MyMockedEventArgs' (inheriting from System.EventArgs) the event can be raised without it complaining about passing through an inappropriate type.

mockedObject.When(
    Sub(x) x.MyRoutineThatInvokesMyMockedEvent( 999 )).Do( 
        Sub(y) RaiseEvent IMockObject.MyMockedEventEventHandler() )

But its here where my suspicions of VB.NET doing some black magic come into play as I'm aware that VB.NET with create the delegates for the event behind the scenes. Of course, the fact that Intellisense doesn't show the EventHandler doesn't particularly help either and I'm guessing I could manually code up the delegate but this approach seems quicker.

HTH

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top