Rhino Mocks:如何使用vb.net和AAA语法验证方法只调用一次

时间:2010-09-26 15:09:27

标签: vb.net unit-testing rhino-mocks

我正在尝试使用Rhino Mocks中的AAA语法和VB.Net来验证方法只被调用一次。我似乎无法做对。使用此代码,如果存储库被调用两次,则在第二次调用时不返回任何内容,并且测试通过。我希望在调用VerifyAllExpectations时测试失败。

<TestMethod()>
Public Sub GetDataCallsRepositoryOneTime()
    Dim repository As IDataRepository = MockRepository.GenerateMock(Of IDataRepository)()
    Dim cacheRepository As New CachingDataRepository(repository)
    Dim results1 As IEnumerable(Of DataItem)
    Dim results2 As IEnumerable(Of DataItem)

    'verify that the base repository was asked for its data one time only
    repository.Expect(Function(x) x.GetData(1)).Return(GetSampleData).Repeat.Once()

    results1 = cacheRepository.GetData(1)
    results2 = cacheRepository.GetData(1)

    sdr.VerifyAllExpectations()
End Sub

2 个答案:

答案 0 :(得分:4)

如果您使用的是VS2010,则会获得much improved lamba support(包括使用Rhino Mocks和VB的更好体验)

我概述了如何使用AAA语法w / rhino mocks here(使用c#)但是要快速回答你的问题,你可以做以下事情

首先要验证一些交互行为的类(超级简单但有效)

Public Class Class1
    Public Overridable Sub Happy()

    End Sub

    Public Overridable Sub DoIt()
        Me.Happy()
        Me.Happy()
    End Sub
End Class

接下来,使用AAA + vb编写的测试证明Happy方法被称为2x

<TestClass()>
Public Class UnitTest2

    <TestMethod()>
    Public Sub TestMethod1()
        Dim x = MockRepository.GeneratePartialMock(Of Class1)()

        x.DoIt()

        x.AssertWasCalled(Sub(y) y.Happy(), Sub(z) z.Repeat.Times(2))
    End Sub

End Class

答案 1 :(得分:-1)

由于AssertWasCalled与VB不兼容,我有以下(丑陋)解决方案和演示代码

Public Interface datarepository
    Function GetData(ByVal id As Integer) As IEnumerable(Of String)
End Interface

Public Class cacherepository
    Dim _datarepository As datarepository
    Dim results As New Dictionary(Of Integer, IEnumerable(Of String))

    Public Sub New(ByVal datarepository As datarepository)
        _datarepository = Datarepository
    End Sub

    Public Function GetData(ByVal id As Integer) As IEnumerable(Of String)
        Dim result As New List(Of String)
        If results.TryGetValue(id, result) = False Then
            result = _datarepository.GetData(id)
            'Uncomment the following line to make the test pass'
            'results.Add(id, result)'
        End If
        GetData = result
    End Function
End Class

<TestClass()>
Public Class UnitTest1

    <TestMethod()>
    Public Sub TestMethod1()
        Dim datarep As datarepository = MockRepository.GenerateMock(Of datarepository)()
        Dim cacherep = New cacherepository(datarep)
        cacherep.GetData(1)
        datarep.Expect(Function(x) x.GetData(1)).Throw(New ApplicationException("FAILED TEST"))
        Try
            cacherep.GetData(1)
        Catch ex As ApplicationException
            Assert.Fail("GetData is called more than once")
        End Try
    End Sub

End Class