In the previous text on AssertWasCalled
I presented the Rhino Mocks method for checking whether an object's method was called during test execution.
However, that text silently assumed that a method, with a given set of parameter values, will be called only once during test execution.
So, the following test will pass:
Public Interface IService
Sub Action(X As Integer)
End Interface
Public Class Tester
Public Property Service As IService
Public Sub Run()
Service.Action(1)
Service.Action(2)
End Sub
End Class
<TestMethod()>
Public Sub TestRun()
Dim service As IService = MockRepository.GenerateStub(Of IService)
Dim tester As New Tester With {.Service = service}
tester.Run()
service.AssertWasCalled(Sub(its) its.Action(1))
service.AssertWasCalled(Sub(its) its.Action(2))
service.AssertWasNotCalled(Sub(its) its.Action(3))
End Sub
but this test will fail:
Public Interface IService
Sub Action(X As Integer)
End Interface
Public Class Tester
Public Property Service As IService
Public Sub Run()
Service.Action(1)
Service.Action(1)
Service.Action(2)
End Sub
End Class
<TestMethod()>
Public Sub TestRun()
Dim service As IService = MockRepository.GenerateStub(Of IService)
Dim tester As New Tester With {.Service = service}
tester.Run()
service.AssertWasCalled(Sub(its) its.Action(1))
End Sub
The test failure message will read:
Test method TestRun threw exception:
Rhino.Mocks.Exceptions.ExpectationViolationException: IService.Action(1); Expected #1, Actual #2.
So, basically, what it's saying is that we asserted that Action(1) will be called exactly once, but it was actually called twice - hence the failure.
Turns out that AssertWasCalled has one additional optional parameter - setupConstraints - that allows you to specify call counts; like so:
<TestMethod()>
Public Sub TestRun()
Dim service As IService = MockRepository.GenerateStub(Of IService)
Dim tester As New Tester With {.Service = service}
tester.Run()
service.AssertWasCalled(Sub(its) its.Action(1),
Function(options) options.Repeat.Times(2))
End Sub
The repeat method allows you to specify the count of calls by using one of the following (self-explanatory) calls:
- .AtLeastOnce(),
- .Once() - equivalent to not using any options at all,
- .Times(count) - exact count of calls,
- .Times(min, max) - range of count of calls,
- .Twice().
<TestMethod()>
Public Sub TestRun()
Dim service As IService = MockRepository.GenerateStub(Of IService)
Dim tester As New Tester With {.Service = service}
tester.Run()
service.AssertWasCalled(Sub(its) its.Action(2),
Function(options) options.Repeat.AtLeastOnce)
service.AssertWasCalled(Sub(its) its.Action(2),
Function(options) options.Repeat.Once)
service.AssertWasCalled(Sub(its) its.Action(1),
Function(options) options.Repeat.Times(2))
service.AssertWasCalled(Sub(its) its.Action(1),
Function(options) options.Repeat.Times(1, 3))
service.AssertWasCalled(Sub(its) its.Action(1),
Function(options) options.Repeat.Twice)
End Sub
HTH
Top
|