«

»

Mar 06

Part 1 — SharePoint Retreat–TDD and Unit Testing, the methodology used.

In my last post about the SharePoint retreat, I waxed lyrical about the costs of unit testing and why you may or may not want to get into Unit testing your code. Stepping on from this is how do we go about unit testing a SharePoint project in Visual Studio 2010? What tools do we need and what methodology do we need to follow? Just to be clear, I’ve never unit tested anything in SharePoint before yesterday, this is all my takeaway from SharePoint retreat. For a more expert view on TDD and SharePoint, start with Andrew Woodwards blogs and slide decks on the subject and go from there… http://www.21apps.com/agile/

Because of the length that this will turn into, I’m going to break it into several posts.

  1. SPRetreat TDD – a retrospective (See what I did there-)
  2. Part 1 — SharePoint Retreat–TDD and Unit Testing, the methodology used.  (this one..)
  3. Part 2 – SPRetreat TDD and Unit Testing, the methodology used cont..

What’s involved?

The rules of the day were:-

    1. You are not allowed to write any production code unless it is to make a failing unit test pass.
    2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
    3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

These rules, coupled with the Red, Green, Refactor (see later) aim to produce lean readable code.

The aim of the day is to write a web part for SharePoint that contains a magic 8 ball. You’ll be able to ask it questions and the Magic 8 Ball will automagically select the answer you need from a SharePoint list.

In order to make the unit testing possible and also to improve the experience, I’m using several tools recommended by Andy for the day.

So what are they?

  1. NUnit provides the actual unit testing framework, without it we wouldn’t have our unit tests. There are other options such as MSTest available.
  2. Resharper V5 – Provides the refactoring tools (plus other functionality), Some of which is already available in VS2010. This is my first time using it, but I quite like it. Takes some getting used to.
  3. TestDriven.net – This is a VS2010 plugin that makes the process of testing easier, for instance tests can be run by key press and the output sent to the Output window rather than a pop up GUI. It’s all about speed remember.
  4. TypeMock – Mocking and isolation framework. Frankly if you want to truly isolate the SharePoint part of your SharePoint code, TypeMock is probably going to be a must. Without it, the amount of isolation you can do is reduced, but not removed entirely.

The unit tests themselves have been written in the following form and I made sure that through the day I used the //Arrange //Act //Assert tags throughout to remind me where I was in the test and what I’m doing..

Public void Method_Scenario_Behaviour()
{
       //Arrange

       //Act

      //Assert

}

In the test above, we’re arranging or setting up the test, We’re taking an action on the object or method and then asserting that the behaviour does what we expect. This is the basic concept for all of the tests, sometimes though you’ll bring some of the stages such as Act and Assert into a single line. (You’ll see this when asserting an exception.)

Getting into the code.

As the retreat was about developing good skills and muscle memory, we did several sessions during the day, REPEATING all the steps from the previous session, each time progressing further down the road to our finished product. Following each session, in a true Agile fashion we held a retrospective and reviewed each others code. This was invaluable as seeing several peoples view points on the tests did open your eyes to other possibilities. The code I’m going to develop whilst posting this blog will hopefully take us all the way to a finished SharePoint web part that utilises the Magic 8 Ball TDD code.image

On my SharePoint VM, I’ve fired up Visual Studio 2010 and created an empty Visual Studio Solution. To this I’ve added 2 projects, The first is my Test code and the second is my Production code. Andy suggested that we use this method with the Production code sitting in the parent namespace and the test code sitting in Parent.Test. Each namespace then contains the relevant named class E.g. Parent.Ball and ParentTest.BallTest.

Your solution should look something like this:-

 

  • Add a reference to NUnit.Framework.dll in your test project.
  • Add the attribute [TestFixture] to your BallTest class. You’ll note that of course Visual Studio isn’t aware of this attribute, however Resharper is aware of your referenced objects and highlights the suggestion to you. Click on this and the relevant using statement will be added.
  • image

 

  • The next section of code is our first test and all of our subsequent tests will use this format or a variant of. I’ve also used Resharper’s template function to create a snippet of this test so that I can quickly add a new function. (It’s all about speed and muscle memory don’t forget, less mouse means more coding!)
  • If you’re typing this through yourself, another Resharper helper pops up when typing the //Arrange part out. We haven’t told the test class about the actual production code yet, so when we try and reference it, we can’t.image

 

 

 

  • Note: A TDD purist would point out that I shouldn’t have created the Magic8Ball production class until I’d written a test that failed… Erm, I’m beginning at this and getting my head around it..give me a break..  Smile
  • Now that we’ve got an object to play with, We’ll start with our first action and call the balls AskQuestion method with a simple string. image

 

 

  • Wait a minute, we’ve got what would be a compile error! That’s a failed test.. we’re getting into true TDD territory now! Using Resharper, we’ll create the method that we’re calling.
  • VS2010 will switch to the production code and you’ll find that we now have our method, complete with return type, parameters and Not Implemented Exception.
namespace Magic8Ball
{
    public class Ball
    {
        public string AskQuestion(string s)
        {
            throw new NotImplementedException();
        }
    }
}
  • Back in our test class, we’ll add our Assert, Your test code will look something like this:-
        [Test]
        public void Ask_Question_ReceiveAnswer()
        {
            //Arrange
            Ball ball = new Ball();

            //Act
            string answer = ball.AskQuestion("q");

            //Assert
            Assert.IsNotNullOrEmpty(answer);
        }
  • Running our first test, Either by using the NUnit icon in the breakpoint border (This will use the GUI), or using a key bind added through the usual VS2010 options/Keyboard menu, bound to Testdriven.Nets RunTests option (Which will use the output window, not as flashy but quick!)
  • Test 'Magic8Ball.Test.BallTest.Ask_Question_ReceiveAnswer' failed: System.NotImplementedException : The method or operation is not implemented.
        Ball.cs(12,0): at Magic8Ball.Ball.AskQuestion(String s)
        BallTest.cs(19,0): at Magic8Ball.Test.BallTest.Ask_Question_ReceiveAnswer()
    
    0 passed, 1 failed, 0 skipped, took 0.44 seconds (NUnit 2.5.5).
  • Remember, we’re sticking to the precept of typing only enough code to fix each test as it fails. We could have changed the "Throw new Not Implemented Exception” statement, but then we’d be breaking the rules! So as expected, our test fails.
  • Switch to the production code, we now write only enough code to fix the test.
  •         public string AskQuestion(string s)
            {
                return "a";
            }
  • Replacing the exception with a valid return. Now re-run the test. (Ideally by now we’re not touching the mouse much!)
  • ------ Test started: Assembly: Magic8Ball.Test.dll ------
    
    1 passed, 0 failed, 0 skipped, took 0.52 seconds (NUnit 2.5.5).
  • So, we’ve failed a test, then passed a test, so using the Red, Green, Refactor rule, we need to look and see if any of the code could be refactored to make it easier to read. As we’re on such a short piece of code now, there’s only one thing that needs amending and that’s the parameter placed in the AskQuestion method, Variable names really need to be meaningful, so we’ll change that “s” to be “question”.

You’ve just written your first bit of test driven code.. but we’re not done yet, We’ve got to get this Magic8Ball class written and tested (Or should that be tested and written?), then we need to get it into SharePoint.

That’ll continue in Part 2. TBC……

1 ping

  1. TDD: Links, News And Resources (19) | Angel "Java" Lopez on Blog

    […] Part 1 — SharePoint Retreat–TDD and Unit Testing, the methodology used. – Blog of an overweight SharePoint addict http://www.myfatblog.co.uk/index.php/2011/03/part-1-sharepoint-retreattdd-and-unit-testing-the-metho… […]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.