Thursday, April 03, 2008

TypeMock - It's well ace.

Recently I purchased a fantastic mock framework called TypeMock and I will recommend any developer who wishes to improve their testing procedures to consider it. There are a number of bloggers out there with plenty of code examples, but here is my contribution. Today I needed to figure out a way that I can mock a SharePoint SPSite obejct, specifically a site object returned via SPContext.Current.Site. I wanted to do this in order for me to be able to run unit tests against my web parts. Before using TypeMock, the only way I could know what my code was up to was by using trace files. Now, I'm able to physically run the web part's code in real time and see whats going on! :) Ok, so here's the test:
    Public Sub SPContext_MockInstance_Test()
        Dim mockSPSite As Mock = MockManager.MockObject(Of SPSite)(New String() {"http://mycomputer:24000"})
        Using recorder As New RecordExpectations
            Dim dumm As SPSite = SPContext.Current.Site
        End Using
        Dim target As BitsAndBobs = New BitsAndBobs
        If mockSPSite.MockedInstance IsNot Nothing Then
            DirectCast(mockSPSite.MockedInstance, SPSite).Dispose()
        End If
    End Sub
OK, so the test code works by mocking the call to SPContext.Current.Site, and when that happens, rather then returning that site object (which never exists anyway) the TypeMock framework returns my testing instance of an SPSite object. This is a very cool feature for me, since I've found testing web parts to be a bit of pain. Looking up articles that show you how to attach the debugger to the w3wp.exe process is handy, but it's so fiddly and often doesn't work (well, for me anyway!), so this is a big improvement on that, and hopefully will speed up my testing and allow me to use various scenarios to test the code.