Unit Test SPSite construction Exceptions with new Isolator method
In our white paper Unit Testing SharePoint Solutions – Getting into the Object Model we needed to use Natural Mocks to allow the testing exceptions that are thrown as part of the the SPSite constructor. Our test code looked like this and although not complicated it introduced another concept that could complicate things for newbies more than necessary.
[Test] public void GetRandomMessage_SiteNotFound_ReturnErrorMessage() { //Arrange using (RecordExpectations expections = RecorderManager.StartRecording()) { expections.ExpectAndThrow(new SPSite("http://invalid_url"), new FileNotFoundException()); } //Act string rndMessage = message.GetRandomMessage("http://invalid_url"); //Assert Assert.That(rndMessage.StartsWith("Error")); Assert.That(rndMessage.Contains("Site could not be found")); }
With the release of V5.1.2 of Isolator for SharePoint a new API has been added to the AAA syntax to support just this scenario.
Isolate.Swap.NextInstance<T>().ConstructorWillThrow();
Our tests will now look like this:
[Test] public void GetRandomMessage_SiteNotFound_ReturnErrorMessage() { //Arrange Isolate.Swap.NextInstance<SPSite>().ConstructorWillThrow(new FileNotFoundException()); //Act string rndMessage = message.GetRandomMessage("http://invalid_url"); //Assert Assert.That(rndMessage.StartsWith("Error")); Assert.That(rndMessage.Contains("Site could not be found")); }
You will agree this is a much easier API and helps to lower the barrier to Test Driven SharePoint development a little bit more. We will be updating our white paper to reflect this change and updating out code over the next few days.
Update 25 Nov 08:
You will also need to add the [ClearMocks] directive to the start of you Test Fixture to ensure Isolator clears up after each test.
[TestFixture] [ClearMocks] public class RandomMessage
Also one of the tests will now fail if you are using the new Isolator for SharePoint with the following error:
TypeMock.TypeMockException:
*** Can not fake non-SharePoint type UnitTest.ObjectModel.RandomMessage with current license. In order to fake non SharePoint types please upgrade to Typemock Isolator Commercial license
See more information at http://www.typemock.com/sharepointpage.php.
I will be following up with the Guys at Typemock to see how much room there will be to support non SharePoint objects in the SharePoint Edition for just these scenarios.
