Doing more unit testing and I ran across this nice article on mocking up TempData. That’s great because tempdata is used a lot in controllers and you need a way to mock it for unit testing. Again, this code is in C#, so I will show you the vb version.
http://weblogs.asp.net/leftslipper/archive/2008/04/13/mvc-unit-testing-controller-actions-that-use-tempdata.aspx
Hres the StubTempDataHttpSessionState class:
Imports System.Web.Mvc
Imports System.Web
''' <summary>
''' HttpSessionState for TempData that uses a custom
''' session object.
''' </summary>
''' <remarks></remarks>
Public Class StubTempDataHttpSessionState
Inherits HttpSessionStateBase
' This string is "borrowed" from the ASP.NET MVC source code
Private TempDataSessionStateKey As String = "__ControllerTempData"
Private _tempDataObject As Object
Default Public Overrides Property Item(name As String) As Object
Get
Assert.AreEqual(Of String)(TempDataSessionStateKey, name, "Wrong session key used")
Return _tempDataObject
End Get
Set(value As Object)
Assert.AreEqual(Of String)(TempDataSessionStateKey, name, "Wrong session key used")
_tempDataObject = value
End Set
End Property
End Class
And heres the context class:
Imports System.Web
Public Class StubTempDataHttpContext
Inherits HttpContextBase
Private _sessionState As StubTempDataHttpSessionState = New StubTempDataHttpSessionState()
Public Overrides ReadOnly Property Session As HttpSessionStateBase
Get
Return _sessionState
End Get
End Property
End Class
Heres an example of using this in a unit test. I created a new instance of the TempDataDictionary and set the controllers tempdata to it. Then I load my populated view model into it.
currentController.TempData = New TempDataDictionary()
currentController.TempData(currentController.PendingResultsViewModelTempDataKey) = thisModel
Then I can get the view model out in the controller. Pretty sweet.
thisModel = TempData(PendingResultsViewModelTempDataKey)