Search code examples
vb.netunit-testingrhino-mocks

Rhino Mocks: How to verify a method was called exactly once using vb.net and AAA syntax


I am trying to use the AAA syntax in Rhino Mocks with VB.Net to validate that a method was called only one time. I can't seem to get it right. With this code, if the repository is called twice, it returns nothing on the second call, and the test passes. I would have expected the test to fail when VerifyAllExpectations was called.

<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

Solution

  • If you are using VS2010 you get much improved lamba support (including a much better experience using Rhino Mocks with VB)

    I outline how to use AAA syntax w/ rhino mocks here (using c#) but to answer your question quickly you could do the following

    First the class you want to verify some interactive behavior (super simple but it works)

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

    Next the test written using AAA + vb to prove the Happy method gets called 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