Question

This seems really simple, but I can't seem to get it to work. I want to unit test my controller's assign action. It takes a IEnumerable(Of Integer) which represent the ID's of all the objects to assign.

Here's the code I've written, I'm getting an error on the Do statement (I copied the code from Ayende's blog here http://ayende.com/blog/3397/rhino-mocks-3-5-a-feature-to-be-proud-of-seamless-do).

    <Test()> _
    Public Sub Assign_Post_Should_Assign_All_Audits_Provided()
        Dim auditsToAssign As IEnumerable(Of HvacAudit) = HvacAuditsGenerator.GenerateAudits() _
                                                                .Unassigned()

        Dim auditIDs As IEnumerable(Of Integer) = auditsToAssign.Select(Function(audit, index) audit.HvacAuditID)

        Dim hvacAuditRepo As IHvacAuditRepository = MockRepository.GenerateMock(Of IHvacAuditRepository)()
        hvacAuditRepo.Stub(Sub(repo) repo.GetAuditByID(1)) _
            .Do(Function(invocation) invocation.ReturnValue = auditsToAssign.Single(Function(audit) audit.HvacAuditID = invocation.Arguments(0)))

        Dim controller As New HvacAuditController(hvacAuditRepo)
        Dim r As ViewResult = controller.Assign(auditIDs).AssertViewRendered()

        r.AssertAssignedAuditCount(auditsToAssign.Count)
        auditsToAssign.AssertAreAssigned()
        hvacAuditRepo.AssertWasCalled(Sub(h) h.SaveChanges())
    End Sub
Was it helpful?

Solution

I was able to fix this by changing the code to use a function lambda instead of a sub lambda and return the value directly. I'm not sure what Ayende's blog was referring to.

<Test()> _
Public Sub Assign_Post_Should_Assign_All_Audits_Provided()
    Dim auditsToAssign As IEnumerable(Of HvacAudit) = HvacAuditsGenerator.GenerateAudits() _
                                                            .Unassigned()

    Dim auditIDs As IEnumerable(Of Integer) = auditsToAssign.Select(Function(audit, index) audit.HvacAuditID)

    Dim hvacAuditRepo As IHvacAuditRepository = MockRepository.GenerateMock(Of IHvacAuditRepository)()
    hvacAuditRepo.Stub(Sub(repo) repo.GetAuditByID(1)) _
        .Do(Function(auditID as Integer) Return auditsToAssign.Single(Function(audit) audit.HvacAuditID = auditID))

    Dim controller As New HvacAuditController(hvacAuditRepo)
    Dim r As ViewResult = controller.Assign(auditIDs).AssertViewRendered()

    r.AssertAssignedAuditCount(auditsToAssign.Count)
    auditsToAssign.AssertAreAssigned()
    hvacAuditRepo.AssertWasCalled(Sub(h) h.SaveChanges())
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top