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:
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.Public Sub SPContext_MockInstance_Test()Dim mockSPSite As Mock = MockManager.MockObject(Of SPSite)(New String() {"http://mycomputer:24000"})Using recorder As New RecordExpectationsDim dumm As SPSite = SPContext.Current.Siterecorder.Return(mockSPSite.MockedInstance)
End UsingDim target As BitsAndBobs = New BitsAndBobstarget.Testy()If mockSPSite.MockedInstance IsNot Nothing ThenDirectCast(mockSPSite.MockedInstance, SPSite).Dispose()
End IfEnd Sub