Interesting news on test SharePoint

Typemock announced today a new product Isolator for Sharepoint – which allows unit testing of Sharepoint code without needing Sharepoint installed. Now this is something I have been using the full version of Isolator for of late, and there are more blog posts on the way from me, so watch this space.

So if you are a Sharepoint developer this is an important product you should a least have a look at.

It is also interesting to see the promotion mechanism being used to get the word out onto the blogs, free license to the first 50 bloggers. So I would like to state my position here, I already have a Typemock Isolator license so this post has been written without the carrot of a free license, just written by an very impressed user.

Back from DDD7

Another long day over the weekend at DDD7, but worth it. An excellent selection of sessions; I particularly liked Ben Hall’s on Pex and Jon Skeet’s on Linq.

A big thank you to the organisers for putting on such a successful event. It was noticeably fuller than past events, as we know DDD7 filled up in about four hours. Maybe time for a bigger venue, but would we lose the atmosphere?

The other option is for DDD style events around the country and to this end there were a few announcements yesterday. We already know about DD Scotland in May 2009, the new ones announced for Q2 2009 were

  • SQLBits 4 (Manchester)
  • Developer Day South West (Exeter)

Look out for more details was the organiser‘s call for speakers

Entering a license key for Typemock Isolator if you are not administrator

To license an installation of Typemock Isolator you run the Configuration tools and type in the key, you don’t get the option to enter the key during the installation. When I tried to run this tool today I got the error

image

Now at first I thought it might be that I was on a64bit OS and it was looking in a portion of the registry for 32bit applications. However I was wrong it was far simpler than that.

I am no longer running as administrator on my development box, so when I installed Typemock I was asked for elevated privileges via the UAC and all was OK. The configuration tool also needed to run at this privileges so it could update the registry, so the simple fix is that you just need to call the tool with a RunAs option and all is OK

Windows 7 on the Dell Mini

I don’t recommend having automatic update switched on (which is the default) for Windows 7. Yesterday my Windows 7 install decided to install 20 updates. It rebooted and then rebooted again and again. My guess is that a driver updated and killed the boot process.

It did try to go into the automatic fix, but this just said it could not fix the issue, maybe it was a driver issue. I could not find an equivalent to safe mode to try to delete the updates, so today I am re-installing. This time making setting a system restore point so I can rollback if the same happens again

TypeMock Isolator, SPTypeMock and SharePoint testing

I had to work unexpectedly from home yesterday, this has given me a chance to look at TypeMock Isolator and SPTypeMock to aid in the testing of SharePoint without the normal disturbances of being in the office.

First thing I have to say is TypeMock is an amazing tool, OK it costs some money, unlike RhinoMocks, but it’s ability to mock out sealed classes that have no public constructors is essential when testing SharePoint (which seems to contain nothing but sealed classes with no public constructors).

I decided to try to retro-fit some tests to an old existing WebPart.This was a simple contact form that populated some combo-boxes from SPList collections then saved it’s results to another SPList. This had all been coded making direct calls to the SPList objects as required from within the WebPart. All very old school VB6 style, no MVC pattern, so a block of legacy code that is hard to test. However, the beauty of using this mocking framework is that all you production code remains unaltered (though as we will see there is a good argument for designing/refactoring to aid testing).

I first started with the SPTypeMock library. This CodePlex project has been produced by a pair of MOSS MVPs Carlos Segura (http://www.ideseg.com) and Gustavo Velez (http://www.gavd.net ). It provides a set of wrapper classes in the form MockSPList etc. classes that you can use to construct the the SharePoint mocks, basically they hide some of the TypeMock constructions. This means that test logic ends as follows (using the sample from CodePlex)

Mocking a List Collection
– Method to be tested:

        public static string TestMock_02()
        {
            string strReturn = String.Empty;
            try
            {
                using (SPSite mySite = new SPSite("http://MiServidor"))
                {
                    using (SPWeb myWeb = mySite.OpenWeb())
                    {
                        int intTeller = 0;
                        foreach (SPList oneList in myWeb.Lists)
                        {
                            Debug.WriteLine(oneList.Title);
                            intTeller++;
                        }
                        strReturn = intTeller.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                strReturn = ex.ToString();
            }
            return strReturn;
        }



– Mocking method:

        [TestMethod]
        public void TestMethod2()
        {
            MockSPSite mockSite = new MockSPSite("TestSite");          
            MockSPWeb mockWeb = new MockSPWeb("TestWeb");  
 
            MockSPList mockList0 = new MockSPList("MyList0");         
            MockSPList mockList1 = new MockSPList("MyList1");      
            MockSPList mockList2 = new MockSPList("MyList2");
            mockWeb.Lists = new MockSPListCollection(new[]             
               {
                   mockList0,
                   mockList1,
                   mockList2
               });
 
            mockSite.Mock.ExpectGetAlways("RootWeb", mockWeb.GetInstance()); 
 
            SPWeb WebMocked = mockWeb.GetInstance();    
 
            using (RecordExpectations recorder = RecorderManager.StartRecording())    
            {
                SPSite SiteMocked = new SPSite("");    
                recorder.ExpectAndReturn(SiteMocked.OpenWeb(), WebMocked);    
            }
 
            string expected = "3";   
            string actual;
            actual = Program.TestMock_02();
            Assert.AreEqual(expected, actual);
        }


This works well, they have done a good job. You get a more readable way to express standard TypeMock structure. Yes, the SPTypeMock library is missing some bits, but is a first release and they make point out there is work to do themselves. You can always just write the mocks yourself as in basic TypeMock tests.



However, I did not stop looking here, after doing a bit more reading I started to look at  Isolators' new AAA library (Arrange, Act, Assert) which I think first shipped with  5.1.0. This aims to hide much of the mocking process inside Isolator, by default an ‘empty fake’ is created for everything in the object tree being mocked and you just set values for the bits you care about. This makes it very easy to create a fake of a large system such as Sharepoint by using the magic Members.ReturnRecursiveFakes option



This allowed me to greatly reduce the code required to setup by tests. I create a fake SPSite (and all the object under it) and then set the values for just the items I care about for the test.



 



SPSite fakeSite = Isolate.Fake.Instance<SPSite>(Members.ReturnRecursiveFakes);
           Isolate.Swap.NextInstance<SPSite>().With(fakeSite);



           Isolate.WhenCalled(() => fakeSite.RootWeb.Lists["Centre Locations"].Items).WillReturnCollectionValuesOf(
               new List<SPItem> {
                   Isolate.Fake.Instance<SPItem>(),
                   Isolate.Fake.Instance<SPItem>(),
                   Isolate.Fake.Instance<SPItem>() });



           Isolate.WhenCalled(() => fakeSite.RootWeb.Lists["Centre Locations"].Items[0]["Title"]).WillReturn("Title1");
           Isolate.WhenCalled(() => fakeSite.RootWeb.Lists["Centre Locations"].Items[0]["Email Address"]).WillReturn("email1@email.com");



           Isolate.WhenCalled(() => fakeSite.RootWeb.Lists["Centre Locations"].Items[1]["Title"]).WillReturn("Title2");
           Isolate.WhenCalled(() => fakeSite.RootWeb.Lists["Centre Locations"].Items[1]["Email Address"]).WillReturn("email2@email.com");



           Isolate.WhenCalled(() => fakeSite.RootWeb.Lists["Centre Locations"].Items[2]["Title"]).WillReturn("Title3");
           Isolate.WhenCalled(() => fakeSite.RootWeb.Lists["Centre Locations"].Items[2]["Email Address"]).WillReturn("email3@email.com");



This I think makes the unit testing of business logic within SharePoint viable without having to jump through too many hoops.



Given the choice between the SPTypeMock and the AAA syntax I think I would stick with the latter, but you never know in the future. I suppose it will all come down to which syntax gives the quickest (and maybe more importantly easiest to read) tests in the future.



I did say said I would come back to the application under test’s architecture. This simple WebPart, which contain a good selection of calls to SPLists and had client side validation has proved to be very hard to test, as you would expect. OK you have used TypeMock to get data into it, but how do you test it is in the right field? You can try to render the control but here are issues of WebPartManagers and script registration that frankly are not worth trying to fix. The better solution is some design for test, which I think for WebParts means MVC. In some ways this pattern would negate the need for TypeMock as you would create an IDataModel interface and have any test version you require, though of course you could mock this with TypeMock.



All this said I am hugely impressed by TypeMock Isolator, a really powerful tool for the testing of complex platforms like SharePoint

Strange guide to Ruby

At the XP Club last night I was pointed at a web site that contains a very strange guide to Ruby ”Why’s (poignant) guide to Ruby”. This is one of strangest language books I have read in a while, probably since “Mr Bunny’s Guide to Active X”, which was described in its own blurb…

“This is the first technology book by Carlton Egremont III, author of numerous lengthy grocery lists (unpublished), one or two letters to his mom (unsent), and a doodle on page 117 of the Rochester Public Library's copy of Moby *** (overdue). Mr. Bunny's Guide to ActiveX makes a lovely gift for the nerd who has everything, and is perfect for propping up uneven table legs. For the high-tech parent there is simply no better antidote to yet another bedtime reading of "The Velveteen Rabbit" or the "OLE 2 Programmer's Reference". Just like Carlton, you and your children will come to believe in a talking bunny, a befuddled farmer, and a technology called ActiveX. “

The strangest thing about these books is they are both a really good introduction to their subjects. As we have seen with the Head First series of books, training material can come in many forms, because people learn in many ways.

TFS Power Toys

I am not a fan of blog posts that are just a repeat of an announcement on other blogs, but in this case I think it is worth noting that the TFS October 2008 Release of the Power Toys are out.

The power toys are always interesting but the point of note here is the new shell integration for TFS. This means you can check in/out from Windows Explorer, thus in effect making it far easier to integrate third party products with TFS, like Dreamweaver or Expression Blend (OK not third party but has no TFS integration until version 3).

XPClub meeting on 12th November

Next weeks meeting is at the Victoria Hotel in Leeds as usual at 7pm. It is going to be group discussion sort of session, the subjects being:

Daniel Drozdzewski is going to present the future of the computing (based on the article read in recent New Scientist about processors built on logic gates utilising the chaos phenomenon)

plus

moderated conversation about design in software projects

plus the usual gossip from the industry.

Hope to see you there, remember the event is free and so it at least the first beer.

NB. Remember next months meeting on the 10th of December is Gary Short’s excellent session on Patterns in software development