I am working on a project that uses session and application level calls nested deep within the code. It is not practical to refactor those calls to pass in the values needed and make Unit Testing possible through dependency injection, so I needed to find a way to create automated tests that would not crash on those calls. I researched and tried out many different approaches. Ultimately what I came up with was to use Microsoft's Fakes to mimmic the Session and Application calls. I was helped greatly by this post,Testing Untestable Code Thanks to MS Fakes, and commented my code with his link in case others at my company need to view it.
I created a class that my Web Tests can inherit from that will handle the setup of these Fake calls.
I created a class that my Web Tests can inherit from that will handle the setup of these Fake calls.
Imports System.IO Imports System.Web Imports System.Web.Fakes Imports Microsoft.QualityTools.Testing.Fakes <TestClass()> Public Class SessionTestBase Private _fakeHttpContext As IDisposable <TestInitialize()> Public Sub BeforeEachTestBase() _fakeHttpContext = ShimsContext.Create System.Web.Fakes.ShimHttpContext.CurrentGet = Function() Return New HttpContext(New HttpRequest("", "http://tempuri.org", ""), New HttpResponse(New StringWriter())) End Function SetupSessionState() SetupApplicationState() End Sub 'http://blog.christopheargento.net/2013/02/02/testing-untestable-code-thanks-to-ms-fakes/ Private Sub SetupSessionState() Dim sessionState As New System.Web.SessionState.Fakes.ShimHttpSessionState sessionState.SessionIDGet = Function() Return "1" End Function Dim sessionDictionary As New Dictionary(Of String, Object) sessionState.ItemSetStringObject = Sub(key As String, value As Object) sessionDictionary.Add(key, value) End Sub sessionState.ItemGetString = Function(key As String) If sessionDictionary.ContainsKey(key) Then Return sessionDictionary(key) Else Return Nothing End If End Function System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet = Function(o As Object) Return sessionState End Function End Sub Private Sub SetupApplicationState() Dim applicationState As New ShimHttpApplicationState Dim applicationDictionary As New Dictionary(Of String, Object) applicationState.ItemSetStringObject = Sub(key As String, value As Object) applicationDictionary.Add(key, value) End Sub applicationState.ItemGetString = Function(key As String) If applicationDictionary.ContainsKey(key) Then Return applicationDictionary(key) Else Return Nothing End If End Function System.Web.Fakes.ShimHttpContext.AllInstances.ApplicationGet = Function(o As Object) Return applicationState End Function End Sub <TestCleanup()> Public Sub AfterEachTestBase() If _fakeHttpContext IsNot Nothing Then _fakeHttpContext.Dispose() End If End Sub End Class
Comments
Post a Comment