BM-Bloggers

The blogs of Black Marble staff

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 Dick (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.

Microsoft Arc

I am a bit partial to trying out new Microsoft hardware :), Over the weekend I received a Microsoft Arc 

The Arc Mouse’s is a full size mouse which has a brilliant folding back plate its foldable shape allows it to easily half in size and a natty carrying bag . Its micro transceiver clicks into the underside of the mouse using a magnet. The micro transceiver is super small (< 1cm) so it can be left in the laptop while travelling.

Microsoft hardware seems to be using more and more magnets (since the zune earphones) to finish up great designs and adding magnets to the bag just makes it sooo sweet

I however within 24 hours seem to have lost my Arc and my old Notebook 7000 turned up in its place!

b.

Neverwhere but here …

I thought I would take this opportunity to post about what I’ve been reading.

Neil Gaiman seems to be one of those writers that geeks love to love – usually starting with “The Sandman”, but many enjoying his novels too.  Even non-geeks have been exposed through “Stardust”, the movie.  Having only become a fan of Neil Gaiman’s writing (his books, not his comics) in the last few years, I am not surprised to find that I missed the TV Series, “Neverwhere” when it was first shown in 1996. 

Finally got around to reading the book version – the interesting thing is that the TV Series came first, the first edition of the book was written as the series was filmed.  I understand the major difference with the book (based on Neil’s intro in my edition) is that he included everything they didn’t want in the series … as well as including some things he had originally left out for the US publication.  I wouldn’t call it the best book he’s ever written – it’s an interesting twist and commentary on London ‘above’, one that has been used again by others, with some even crediting Gaiman’s book in their own (“UnLunDun”).  The key appears to be that yes, there really is an Angel called Islington, and yes there is an Earl holding Court too and so on.  The story is told through the eyes of Richard, from London ‘above’, having found himself pulled reluctantly (as all good heroes are) into the perils of London ‘below’.

The most interesting characters are the shadier ones (Mr. Croup and Mr. Vandemar), even on the side of ‘good’(the Marquis) whereas the two main characters appear to spend more time reacting (Door and Richardrichardmayhewdick) than initiating.

L.

A Peek into the Geek Den …

Ever wondered what it takes to keep geeks happy?  Running HR for a company full of hardcore geeks means more than keeping the milk fresh and the lights switched on.

Black Marble is a deeply technical software house, and that means our staff are mostly developers.  And it's one of my responsibilities to ensure that our developers have a comfortable working environment.  It's not easy keeping a geek house - it has needs unlike any other office ... more kinds of pop (soda) than you can imagine (on any given day, you can find 7 different varieties of Coke ... and that's not counting the guest cokes that accompany our conference-hopping staff back to our fridge).  On top of that ... there's the eerie glow coming from many corners of the office at lunchtime ... when the Halo wars break out!  Plus all those gadgets ... contrary to popular opinion, they don’t just appear overnight!

On top of that, some of the younger generation of geeks are lacking an understanding of their cultural beginnings … I mean how could they not have seen “Blade Runner” ??

So I will take this opportunity (and this blog …) to share with you what makes geeks tick.

L.

Windows 7 on the Dell Mini 9

Windows7

What better way to try Windows 7 then installing it on the Mini 9? Having read all the commentary about the smaller footprint of the new OS I couldn't resist.

If you want to try this yourself, the procedure is exactly as if you were installing Vista. You will need the drivers folder from the Dell, along with the contents of the Program Files\Wireless Select Switch folder from the XP install and the R192569.exe file from the ZIPFILES folder which is on the support CD I believe.

Installing Windows 7 is a pretty quick and easy process - much faster than Vista. Once installed, follow the same procedure as with Vista to install the hardware drivers from the drivers folder you copied, then run the R192569.exe installer to get the battery driver on. Finally, copy the Wireless Select Switch folder into c:\program files and add an icon to your startup group which fires up the WLSS.exe program - that will allow you to toggle Bluetooth and wireless LAN on and off.

Once that's done, follow the steps that Paul Thurrott  has on WinSuperSite about enabling the 'awesome bar' (does anybody else besides me hate that name?).

I then installed AVG AntiVirus. The corporate version we have failed completely to install, so I turned to AVG Free. That installed fine, but complained at first about being unable to start the resident scanner. A couple of reboots and updates sorted that with no intervention from me and it now works fine.

Office and Live Writer are now installed and I have 4Gb free of my 16Gb SSD. I haven't fiddled with performance tuning yet - the OS ticks over using about 550Mb of RAM. With Live Writer and Internet Explorer 8 running I have about 300Mb of RAM free.

First impressions? Great! Quick, easy to install, UAC is improved, like the new Taskbar UI... I now want to try out some of the other features such as Bitlocker To Go. I hope to get a Server 2008 R2 test environment running as well so I can try things like DirectConnect etc. If I make progress, I'll post more.

Bottom line: Windows 7 - the OS the Mini 9 was built for.

Tech Ed 2008 EMEA IT - Day 5 and home time

I’ve been a bit delayed writing this final blog post from Tech Ed EMEA 2008, so I’m back in the UK. The final day at Tech Ed 2008 EMEA IT was not quite as session filled as previous days, mainly because Rik and I had to be heading off to the airport shortly before 3pm to catch our flight home.

The first presentation of the day was on getting the most out of WSUS 3.0 SP1. One of the items that was mentioned was the arrival of WSUS 3.0 SP2; this is currently in the planning phase and aims to fix the top customer and partner issues seen. It will also install on Windows Server 2008 R2. A number of scenarios for WSUS were discussed, including larger numbers of clients, branch offices and disconnected clients (submarines being the example used!) and some best practices discussed. If the video of this talk is available (at the time of writing, it isn’t unfortunately) and you use WSUS, I’d recommend watching it.

The second (and last) talk of the day I went to discussed Exchange 2007 SP1 and Hyper-V. The good news is that Exchange 2007 SP1 is fully supported on any of the x64 hypervisors validated by Microsoft on Windows Server 2008. If you want to virtualise your Exchange 2003 installation, you’ll need to use Virtual Server 2005; note that Exchange 2003 is explicitly not supported on Hyper-V.

Following these talks Rik and I spent some time talking to more of the experts in the ask the experts pavilion and got some answers to some long-standing questions.

Our flight home was uneventful, but it seemed rather cold when we stepped out of the plane at Manchester after the week in Barcelona!

MicroFormats are here to stay with OOMPH

I was looking into Micro Formats earlier in the year and so I was really interested to see that the Mix team have produced a MicroFormats Toolkits to help create , consume and use MicroFormats.

There is a IE component to help identify MicroFormats.

A Live Writer Plugin to help create hCards

CSS styles for MicroFormats

check it out below.

b.

 

Physical Security just got a bit harder

Normally when I talk about security I am discussing security about developer , IT or personal ( social engineering ). However this article took my fancy about UCSD Scientists furthering the high tech nature of lock picking by producing a system that makes a working copy of a key based solely on a photograph.

 

b.