I was working on unit testing today for an MVC application and needed to mock up the http context for an action method. I found this article that shows how to do this nicely.
http://bradwilson.typepad.com/blog/2010/07/testing-routing-and-url-generation-in-aspnet-mvc.html
Yeah, I know, you can do this with rhino mock and others. But this works too.
I converted this to VB so I could use it in the same project. Heres the vb code:
Imports System.Collections.Specialized
Imports System.Web
Public Class StubContextForTesting
Inherits HttpContextBase
Dim _request As StubHttpRequestForRouting
Dim _response As StubHttpResponseForRouting
Public Sub New(Optional appPath As String = "/", Optional requestUrl As String = "~/")
_request = New StubHttpRequestForRouting(appPath, requestUrl)
_response = New StubHttpResponseForRouting()
End Sub
Public Overrides ReadOnly Property Request As HttpRequestBase
Get
Return _request
End Get
End Property
Public Overrides ReadOnly Property Response As HttpResponseBase
Get
Return _response
End Get
End Property
End Class
Imports System.Collections.Specialized
Imports System.Web
Public Class StubHttpRequestForRouting
Inherits HttpRequestBase
Private _appPath As String
Private _requestUrl As String
Public Sub New(appPath As String, requestUrl As String)
_appPath = appPath
_requestUrl = requestUrl
End Sub
Public Overrides ReadOnly Property ApplicationPath As String
Get
Return _appPath
End Get
End Property
Public Overrides ReadOnly Property AppRelativeCurrentExecutionFilePath As String
Get
Return _requestUrl
End Get
End Property
Public Overrides ReadOnly Property PathInfo As String
Get
Return ""
End Get
End Property
Public Overrides ReadOnly Property ServerVariables As NameValueCollection
Get
Return New NameValueCollection()
End Get
End Property
End Class
Imports System.Collections.Specialized
Imports System.Web
Public Class StubHttpResponseForRouting
Inherits HttpResponseBase
Public override As String
Public Overrides Function ApplyAppPathModifier(virtualPath As String) As String
Return virtualPath
End Function
End Class