tags:

views:

124

answers:

1

I'm in the process of writing a heap of tests around some custom controllers using Moq in VB. Up until now, I've not had to deal with VB Lambda shortcomings since I've only moqed properties or methods.

That is until this morning when I try also running integration tests using Cassini against my code. I had code to add headers using Response.Headers.Add. I did this so I could easily get the headers collection in unit tests using Moq(Of HttpResponseBase) and a SetupGet for Headers->NameValueCollection. Of course, the code chokes in anything other than IIS7 in Integrated Pipeline mode.

So, I changed my code to use Response.AddHeader, which means my unit tests fail. And since I'm in VB, I can' see a sane way to map the call to AddHeader to the Headers collection since Function() needs a return value in VB.

I see a few entries here about Moq and VB, but no one really has the problem of mapping Subs to something else in Moq.

Has anyone tackled this particular situation in VB using Moq?

+1  A: 

Ugh. Why do the solutions always become apparently AFTER you post. :-)

This is ugly, but it works.

  • Subclass HttpResponseBase.
  • Mock that and set the CallBase to True.

Then override Add/AppendHeader to do Headers.Add. Now you catch any variation people use in code as they all fall into Response.Headers collection. The realy code works regardless of which method you use.

Not as clean as just Moqing Add/Append in C# with callbacks, but it does work.

Dim response As New Mock(Of CustomHttpResponse)
response.SetupGet(Function(r As HttpResponseBase) r.Headers).Returns(New NameValueCollection)
response.CallBase = True


Public Class CustomHttpResponse
    Inherits HttpResponseBase

    Public Overrides Sub AddHeader(ByVal name As String, ByVal value As String)
        Me.Headers.Add(name, value)
    End Sub
    Public Overrides Sub AppendHeader(ByVal name As String, ByVal value As String)
        Me.Headers.Add(name, value)
    End Sub
End Class
claco