I'm trying to raise an event in a mocked interface. I can get this in C#, but for some pain-in-the-butt reason can't get it working in VB.Net. If someone could help me out with this situation, I'd appreciate it. Hopefully I haven't missed the boat conceptually and all I'm missing is some syntax. This is similar to the code I'm working with:
Public Interface ISendable
Event SendMessage(message As String)
End Interface
''**********
Public Interface IPrintable
Sub PrintAnnouncement(announcement As String)
End Interface
'******
Public Class BulletinBoard
Private mPrintable As IPrintable
Public Sub New(sendable As ISendable, printable As IPrintable)
AddHandler sendable.SendMessage, AddressOf GetItOut
mPrintable = printable
End Sub
Public Sub GetItOut(message As String)
'Do some stuff I can verify happened with Moq
mPrintable.PrintAnnouncement(message)
End Sub
End Class
I was hoping to get a test that looked something like this running:
Imports NUnit.Framework
Imports Moq
<TestFixture()> _
Public Class SendMessageTests
<Test()> _
Public Sub canRaiseEvent()
Dim announcement As String = "What the?"
Dim sendable As New Mock(Of ISendable)()
Dim printable As New Mock(Of IPrintable)()
Dim bb As New BulletinBoard(sendable.Object, printable.Object)
'What is the syntax for raising sendable's event?
'sendable.Raise( ....? )
printable.Verify(Sub(d) d.PrintAnnouncement(announcement), Times.Once())
End Sub
End Class
Can anyone help me to complete or correct the line in my test class that begins "sendable.Raise..."? Maybe there is more setup I need to do, but the Moq site didn't seem to indicate this is the case.
Thanks in advance.
You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.
Moq supports mocking protected methods. Changing the methods to protected , instead of private , would allow you to mock their implementation.
Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.
The Moq framework is an open source unit testing framework that works very well with . NET code and Phil shows us how to use it.
With this line your test is green:
sendable.Raise(Sub(e) AddHandler e.SendMessage, AddressOf MockHandler, announcement)
You also need to create a "mock" event handler to make it work:
Sub MockHandler()
End Sub
EDIT:
I'm not a VB guy, so it seams there is a shorter syntax with using an inline anonymous method instead of MockHandler: :
sendable.Raise(Sub(e) AddHandler e.SendMessage, Function() vbEmpty, announcement)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With