user728033 user728033 - 2 years ago 113 Question

Raising events with FakeItEasy in VB.Net to verify that event handler is wired properly

I am attempting to test that the event handlers between an interface and controller are wired properly. The system is set up like the example below:

'Interface for Display
Public Interface IClientLocationView

Event LocationChanged(ishomelocation as Boolean)

Sub DisplayChangesWhenHome(arg1 as Object, arg2 as Object)
Sub DisplayChangesWhenNotHome(arg1 as Object, arg2 as Object, arg3 as Object)

End Interface

Public Class ClientLocationController

Public Sub Start(_view as IClientLocationView)

AddHandler _view.LocationChanged, AddressOf LocationChangedHandler

End Sub

Public Sub LocationChangedHandler(ishomelocation as Boolean)
If ishomelocation Then
_view.DisplayChangesWhenHome(arg1, arg2)
_view.DisplayChangesWhenNotHome(arg2, arg1, arg3)
End If
End Sub

End Class

How do I raise the event with the boolean parameter so that I can test each of the code paths contained within the event handler. I'm not having any luck with the syntax shown on the Google Code homepage.

AddHandler foo.SomethingHappened, AddressOf Raise.With(EventArgs.Empty).Now

'If the event is an EventHandler(Of T) you can use the shorter syntax:'

AddHandler foo.SomethingHappened, Raise.With(EventArgs.Empty).Go

This is what I have so far:

Public Sub VerifyThat_LocationChangedHandler_IsWired()
Dim _view As IClientLocationView= A.Fake(Of IClientLocationView)()

Dim pres As ClientLocationController = A.Fake(Of ClientLocationController)(Function() New ClientLocationController(_view))

'?????? Need to raise the event
'AddHandler _view.LocationChanged, AddressOf Raise.With(EventArgs.Empty).Now

End Sub

Answer Source

When using FakeItEasy versions older than 2.0.0, events should be in the form of an EventHandler delegate:

Event LocationChanged As EventHandler(Of LocationChangedEventArgs)

Public Class LocationChangedEventArgs
    Inherits EventArgs

    Public Property IsHomeLocation As Boolean
End Class

Once this is changed you can now use the event raising syntax:

AddHandler _view.LocationChanged, Raise.With(New LocationChangedEventArgs With { .IsHomeLocation = True })

As of FakeItEasy 2.0.0, this restriction no longer applies. You can see more at the Raising Events documentation, but the trick is to supply the delegate type as a typeparam to Raise.With.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download