如何使用Moq举办活动?

时间:2012-01-31 21:22:01

标签: vb.net events moq

我正在尝试在模拟界面中引发事件。我可以在C#中得到这个,但是因为一些痛苦的原因无法让它在VB.Net中运行。如果有人可以帮我解决这个问题,我会很感激。希望我没有错过概念上的船,我所缺少的是一些语法。这类似于我正在使用的代码:

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

我希望得到一个看起来像这样的测试:

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

任何人都可以帮我完成或更正我的测试类中以“sendable.Raise ...”开头的行吗?也许我需要做更多的设置,但是Moq网站似乎并没有表明情况就是这样。

提前致谢。

1 个答案:

答案 0 :(得分:5)

使用此行,您的测试为绿色:

sendable.Raise(Sub(e) AddHandler e.SendMessage, AddressOf MockHandler, announcement)

您还需要创建一个“模拟”事件处理程序以使其工作:

Sub MockHandler()

End Sub

编辑:

我不是VB的人,因此使用内联匿名方法而不是MockHandler,它的语法更短: :

sendable.Raise(Sub(e) AddHandler e.SendMessage, Function() vbEmpty, announcement)