Archive for the ‘Unit Testing’ Category

Following on from my previous post I thought it only fair to dive down into the code that was shown in that article and give a bit more of an explanation on what is going on.

First of all, some of you may have looked at the sample code and asked “What is the ContextSpecification class that the ShoppingCartContext is derived from?” – fair question and one that deserves to be explained.

Allow me to digress momentarily in order to try and set the context (for you seasoned BDD’rs – pun intended!). I was first introduced to BDD (indirectly) at a session on coding Katas at TechEd 2010 in New Orleans and BDD was not exactly why I had attended the session. The Behavior Driven aspect of the interactive presentation was very brief and at the time I was left with the desire to know more, so before the End of TechEd party I spent time scouring numerous technical and not so technical sites – looking for further details. What I found was far more than I had bargained for; it wasn’t that the tests were written in a natural language sort of way, it was the idea that the code was being driven via tests that were in turn driven by use cases – OMG!!!! You mean that the requirements analyst directly affects the way the tests are written? I had already bought in to the TDD mindset and to me it had made perfect sense, but this was far beyond what I had bargained for. So in true engineering fashion – I tried it out myself and low and behold it worked (albeit in a very sanitized and benign sort of way). Before we go any further, I would highly recommend that you read Dan North’s Introduction to BDD (http://behaviour-driven.org/Introduction); there you will see that many of us may be fortunate to get to step 4 of the steps to enlightenment. In my case I was there and thanks to the intro to BDD I would get to 6 and hopefully on to step 7.

So there I am trying to implement my first set of BDD tests (before code implementation) and I hit my first stumbling block. The Context Specification Framework I had been introduced to at TechEd, Machine.Specification by Aaron Jensen (http://github.com/machine/machine.specifications), had wonderful plugin capabilities for ReSharper but nothing that I could use inside of MSTest; yes I know, “big deal”, “so what”, blah, blah… Well as much as I love ReSharper, I still prefer to run MSTest as it is what is run in my build environments. Therefore anything that I have difficulty running with MSTest will be an even bigger hassle on my build machines. So off I went again, looking for more jewels in the proverbial rain-forest of information and lo-and-behold I came across Eric Lee’s implementation of a base class that uses MSpec (http://blogs.msdn.com/b/elee/archive/2009/01/20/bdd-with-mstest.aspx) called ContextSpecification. It is a superb abstract class that allows me to easily write my BDD style test classes and thereby drive my code implementation.

Now then, we have the MSpec assembly reference and now an abstract class (ContextSpecification) to derive from and as I am a big fan of RhinoMocks (for generating mocks or stubs), let’s throw that into the mix. With this base we are ready to go do some BDD.

As I have stated before, the Requirements are what drive our tests in BDD; more specifically the creation of Use Cases will drive the tests. So going back to the example in my previous post, we will start with the following requirement:

    A customer can add items to their shopping cart.

Strictly speaking, in SCRUM terms, this should be written as follows:

    AS A Customer

    I WANT to be able to add items to a shopping cart

    SO THAT I can keep a collection of items that I want to buy.

From this user story we can expand the Use Cases (I also consider them as Conditions of Acceptance for the User Story) to give me detail to the high level statement:

Scenario 1: Adding items to an empty shopping cart

  • GIVEN that the shopping cart is empty
  • WHEN the customer adds 1 item
  • THEN the shopping cart should contain 1 item

Scenario 2: Adding items to a full shopping cart

  • GIVEN that the shopping cart contains 2 items
  • WHEN the customer adds 1 item
  • THEN the shopping cart should contain the 2 existing items and the 1 new item.

I have purposefully capitalized the GIVEN, WHEN and THEN, simply to draw parallels with the AS A <role> I WANT <functionality> SO THAT <benefit> of SCRUM and hopefully highlight the fact that patterns can be drawn from both and thereby help us to create consistent ways in which to write both User Stories and Use Cases.

Now that we have our Use Cases we can start to create our tests. Taking the first scenario we will need to setup a Shopping cart context; which is where we bring in the ContextSpecification abstract class (remember, we don’t have any implementation code yet):

namespace Bdd.Shopping
{
    public class ShoppingCartContext : ContextSpecification
    {
        /// <summary>
        /// The "Given some initial context" method
        /// </summary>
        protected override void Context()
        {
            // setup your class under test
        }
    }

    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestClass]
    public class UnitTest1 : ShoppingCartContext
    {
        /// <summary>
        /// The "When an event occurs" method
        /// </summary>
        protected override void BecauseOf()
        {
            //
            // TODO: Add behavior setup (Action) here
            //
        }

        /// <summary>
        /// The "then ensure some outcome" method.
        /// </summary>
        [TestMethod]
        public void TestMethod1()
        {
            //
            // TODO: Add test logic here
            //
        }
    }
}

Remember that the use case was written as follows:

  • GIVEN that the shopping cart is empty
  • WHEN the customer adds 1 item
  • THEN the shopping cart should contain 1 item

The “GIVEN” aspect of the use case is the Context() method of our base class – where we initialize our member variables.

The “WHEN” of the use case will be the TestClass – this will be the container for the THEN aspect.

The “THEN” will be the TestMethod and perform the appropriate assert(s).

Putting all of this together we arrive at the following:

namespace Bdd.Shopping
{
    public class ShoppingCartContext : ContextSpecification
    {
        protected ShoppingCart _cart;
    }

    /// <summary>
    /// Test Class for "WHEN the customer adds 1 item THEN the shopping cart should contain 1 item"
    /// use case.
    /// </summary>
    [TestClass]
    public class when_1_item_is_added_to_an_empty_shopping_cart : ShoppingCartContext
    {
        /// <summary>
        /// The "Given some initial context" method
        /// </summary>
        protected override void Context()
        {
            _cart = new ShoppingCart();
        }

        /// <summary>
        /// The "When an event occurs" method
        /// </summary>
        protected override void BecauseOf()
        {
            ShoppingItem item = new ShoppingItem();
            _cart.Add(item);
        }

        /// <summary>
        /// The "then ensure some outcome" method.
        /// </summary>
        [TestMethod]
        public void then_the_shopping_cart_should_contain_1_item()
        {
            Assert.AreEqual(1, _cart.Items.Count);
        }
    }
}

The class name of the TestClass and the method name of the TestMethod help us associate the test with the first use case; “WHEN the customer adds 1 item THEN the shopping cart should contain 1 item”.

In true TDD fashion we have only implemented enough to compile (i.e. absolute minimum of implementation classes) – so this test will fail:

BDD  - Fail First

The next step, of course is to put in the functionality to get the test to pass (TDD mantra – Red, Green, Refactor, Repeat until all test are done). In the case of the implementation classes, we will go from this:

    public class ShoppingCart
    {
        internal void Add(ShoppingItem item)
        {
            throw new NotImplementedException();
        }

        public List<ShoppingItem> Items { get; set; }
    }

    public class ShoppingItem
    {
        public ShoppingItem() {}
    }

To this:

    public class ShoppingCart
    {
        public ShoppingCart()
        {
            Items = new List<ShoppingItem>();
        }

        internal void Add(ShoppingItem item)
        {
            Items.Add(item);
        }

        public List<ShoppingItem> Items { get; set; }
    }

    public class ShoppingItem
    {
        public ShoppingItem() {}
    }

This will give us green in our first test:

BDD  - Then Pass

Now we move on to the next use case:

  • GIVEN that the shopping cart contains 2 items
  • WHEN the customer adds 1 item
  • THEN the shopping cart should contain the 2 existing items and the 1 new item.

Here we see that the Use Case is more specific in that it is requiring us to check that the latest item has been added – we will need to add an identifier to the item be able to check against it in our assertion. This will mean that we will need to run our first test again as we will be changing the implementation classes.

First we write the new Test class and associated Test method and do the minimum implementation to get it to compile.

New Test class and Test method:

    [TestClass]
    public class when_1_item_is_added_to_a_cart_containing_2_items : ShoppingCartContext
    {
        private const string NewItemTitle = "Test Driven Development By Kent Beck";

        /// <summary>
        /// The "Given some initial context" method
        /// </summary>
        protected override void Context()
        {
            _cart = new ShoppingCart();
            ShoppingItem item = new ShoppingItem("Behavior Driven Development By Dan North");
            _cart.Add(item);
            item = new ShoppingItem("Agile Software Development with Scrum By Ken Schwaber and Mike Beedle");
            _cart.Add(item);
        }

        /// <summary>
        /// The "When an event occurs" method
        /// </summary>
        protected override void BecauseOf()
        {
            ShoppingItem item = new ShoppingItem(NewItemTitle);
            _cart.Add(item);
        }

        /// <summary>
        /// The "then ensure some outcome" method.
        /// </summary>
        [TestMethod]
        public void then_the_shopping_cart_should_contain_the_2_existing_items_and_the_1_new_item()
        {
            Assert.AreEqual(3, _cart.Items.Count);
            Assert.AreEqual(NewItemTitle, _cart.Items[2].Title);
        }
    }

Minimum implementation classes:

    public class ShoppingCart
    {
        public ShoppingCart()
        {
            Items = new List<ShoppingItem>();
        }

        internal void Add(ShoppingItem item)
        {
            Items.Add(item);
        }

        public List<ShoppingItem> Items { get; set; }
    }

    public class ShoppingItem
    {
        public ShoppingItem(string title) {}

        public string Title { get; set; }
    }

When we run the test, the first one will still pass, but seeing as we have done the minimum to be able to compile the second test will fail:

BDD  - Then Fail Again

So therefore the next stage is to make the red go green and “back fill” the correct functionality – to update the implementation class as follows:

    public class ShoppingItem
    {
        public ShoppingItem(string title)
        {
            Title = title;
        }

        public string Title { get; set; }
    }

Now when we run the tests all should be green:

BDD  - Then Pass Again

As we continue we are always aligning our code with the use cases and therefore ensuring that we are adding the business value as intended. With the TDD aspect we are also ensuring that any changes we do to the implementation can be done so with the peace of mind that as long as all of the tests past before we go on to the next use case, we will be building robust code.

As I have said in this blog post and the previous one, BDD is a natural evolution of TDD in as much that it adds the linkage from the tests to the requirements. At a personal level it is also a natural progression in my continuous evolution as a software professional and it helps to consolidate my understanding of the requirements more than any type of review ever could.

Make no mistake, BDD and (especially) TDD are a definite shift in mindset mostly in the idea that the test is written first and you only write enough of the implementation to be able to get the test to pass. This puts the onus on the test being right in the first instance and places more significance on the testing aspect of software development.

  • Share/Bookmark

Although many people may have commented so. I have been drawn in and fired up by Behavior Driven Development (BDD) and through various discussions I have found a great number of non-believers and nay sayers who, strangely enough, don’t truly “get” Agile development either. Strange that, isn’t it? The brick wall I sometimes encounter when trying to get the idea of SCRUM across to certain people is that it is “academic and won’t really work for us”, “we can use facets of it, but the thing as a whole just doesn’t fit”. And in a similar way the same arguments came up when I mention BDD.

So let’s refresh our knowledge on BDD before we go any further. Behavior Driven Development was the brain child of Dan North and he has an excellent article about its evolution on his blog (http://blog.dannorth.net/introducing-bdd/). BDD brings together the Requirements Analyst with the Testers and Developers to start breaking down the stories into use cases (may be known as Conditions of Acceptance in a User Story). So what’s new you may ask? Well, those Use Cases, written in natural language become the definitions of the Test Cases and Unit Tests that will drive the code.

What? Test before Code? Unheard of! Charlatan!

Oh please! Really? Yes folks, BDD is sometimes seen as an extension of TDD (Test Driven Development). TDD pushes the testing to the fore and is used to drive the implementation, so rather than waiting until the code is written to create the unit tests, we now create the unit test and write the code to make the test pass. In my mind I see BDD as TDD on steroids! So how does it work?

Imagine the following (benign and fictitious) requirement:

  • A customer can add items to their shopping cart.

This could be expanded into the following use cases (or conditions of acceptance):

Scenario 1: Adding items to an empty shopping cart

  • Given that the shopping cart is empty
  • When the customer adds 1 item
  • Then the shopping cart should contain 1 item

Scenario 2: Adding items to a full shopping cart

  • Given that the shopping cart contains 2 items
  • When the customer adds 2 items
  • Then the shopping cart should contain 4 items

From this we can derive our test cases and the definition of our Unit Tests. Consider the following code:

namespace ShoppingCartExample
{
    public class ShoppingCartContext : ContextSpecification
    {
        protected ShoppingCart _cart;
    }

    [TestClass]
    public class when_1_item_is_added_to_an_empty_shopping_cart : ShoppingCartContext
    {
        ///

        /// The "Given some initial context" method
        /// 

        protected override void Context()
        {
            _cart = new ShoppingCart();

        }

        ///

        /// The "When an event occurs" method
        /// 

        protected override void BecauseOf()
        {
            ShoppingItem item = new ShoppingItem("Behavior Driven Development By Dan North");
            _cart.Add(item);

        }

        ///

        /// The "then ensure some outcome" method.
        /// 

        [TestMethod]
        public void the_shopping_cart_should_contain_1_item()
        {
            Assert.AreEqual(1, _cart.Items.Count);
        }
    }

    [TestClass]
    public class when_2_items_are_added_to_a_shopping_cart_containing_two_items : ShoppingCartContext
    {
        ///

        /// The "Given some initial context" method
        /// 

        protected override void Context()
        {
            _cart = new ShoppingCart();
            ShoppingItem item = new ShoppingItem("Behavior Driven Development By Dan North");
            _cart.Add(item);
            item = new ShoppingItem("Agile Software Development with Scrum By Ken Schwaber and Mike Beedle");
            _cart.Add(item);
        }

        ///

        /// The "When an event occurs" method
        /// 

        protected override void BecauseOf()
        {
            ShoppingItem item = new ShoppingItem("Test Driven Development By Kent Beck");
            _cart.Add(item);
            item = new ShoppingItem("The Art of Unit Testing By Roy Osherove");
            _cart.Add(item);
        }

        ///

        /// The "then ensure some outcome" method.
        /// 

        [TestMethod]
        public void the_shopping_cart_should_contain_4_item()
        {
            Assert.AreEqual(4, _cart.Items.Count);
        }
    }
}

I will go in to more detail about the code in a later blog article. For now we will concentrate on the naming of the classes and Test Methods.

Once we have implemented the code that the tests call, we will see the following results:

BDD Unit Test Results

You can now see how the unit test classes relate to the context of the use case (“Given that the shopping cart is empty” with “When the customer adds 1 item“) and the test methods relate to the result criteria (“Then the shopping cart should contain 1 item“).

The beauty of BDD is that it slams the team into instant interaction; there are no ceremonies, burndowns or roles to allow us to ease into the Agile environment; this is an “in your face”, “get on with it” approach and is an Agile technique that can easily be used within the SCRUM framework. This is also the “ugly” part of BDD, individuals may not be comfortable working in this way and this leads to a bigger question of a right fit for those individuals. The benefits of working introducing BDD to your team are obvious:

  • The clarity of requirements are brought to the fore faster than in any other circumstance – if you can’t write the test, then something is wrong with the requirements and the team will spot that as soon as they sit down to work with the requirements analyst.
  • Unit Tests are written from the beginning and make sense to everyone, even the non-technical members of the group can see how well the design is going, just by looking at the unit tests being run (or not).
  • The design is driven from the requirements – as it should be; why would you write code for anything else? Therefore we see a facet of lean.

The adoption of BDD is by no means easy and it can, as stated before, lead to exposing some deficiencies in the team or environment. This in itself may be a good incentive to adopt; hyper-productive teams are driven to succeed by the very nature of their ease in adopting agile techniques and BDD lends itself to those types of individuals.

  • Share/Bookmark

With this being my third TechEd and first in the United States, it was by far the best Technical Conference I have been to so far. And from all of the presentations, technical discussions and sessions, there is one definite difference to all other Microsoft events that I have been to in previous years – the enthusiasm and willingness to engage the technical users on how they are using Microsoft Products. Several years ago I would never have imagined that Microsoft Staff (Program Managers and Technical staff alike) would have been so willing to engage the users and be open to frank discussions and feedback on their work (i.e. the development tools that are VS 2010, TFS 2010 and Lab Management).

Some of the highlights for me were a number of sessions that I attended:

ASI203 | Understanding the Microsoft Application Server: AppFabric, WF, WCF, and More

(David Chapell) – as ever David was insightful with his delivery, this time on the Service AppFabric from Microsoft, to the point that he highlighted the difference and somewhat confusing reference to Service AppFabric and Azure AppFabric.  With some of the demonstrations provided by Ron Jacobs, the session was invaluable for those that are on the fringe of Azure and the concept of Cloud Computing as well as those that are seasoned SOA implementers. The presentation took us from an explanation on AppFabric (Services) showing us the magic of AppFabric Caching; through using WF in conjunction with WCF to provide an alternative to traditional WCF Services; to using Hosting and Caching together to provide a seamless experience for the end user.

DPR206 | Visual Studio ALM: Lessons Learned through Dogfooding

(Brian Harry) – Brian took us through a journey of discovery as he pulled back the covers on the pains and successes that the Developer Division went through during their progress from VS 2005, 2008 and 2010. He highlighted the influence that the division had on shaping the tools that came to be as well as the influence that the process adoption had on the tools as well – specifically SCRUM. From the presentation of statistics on various metrics gathered in all three release and the comparison between them; to the explanation on how the teams breakdown the features into pillars then groups and then deliverables. This presentation is high on my list of favorite sessions.

DPR207 Why Software Estimation is so Painful and How It Doesn’t Have To Be

(Gregg Boer) – Gregg’s presentation took us through familiar territory (in fact all too familiar territory) and certainly provided us with the assurance that we (developers / software engineers) are not mad as hatters. His portrayal of circumstances and roles were spot-on to the point that it was uncanny to see – (has he been in the same meetings as I had?). This illustrative presentation re-assured me that the circumstances one finds one’s self is not unique and certainly is repeated across the majority of Software Development Companies throughout the world.

DEV08-INT Using Microsoft Visual Studio 2010 to Understand Your Applications

(Mark Groves and Suhail Dutta) – Mark and Suhail’s demos into how to utilize the features of the Architecture tools were very helpful even to someone who has spent sometime playing around with them in the months leading up to Beta and RC. The demonstrations of Layer Diagrams and UML Diagrams were useful to highlight the very important addition of Architectural tools that have been longed for by many in the development community – I for one am seriously ecstatic for such possibilities that can be incorporated into the build. Just the fact of being able to validate the integrity of the architecture in each build is in itself a major improvement and cannot be understated.

DPR03-INT | Increasing Your Productivity Using Code Katas

(David Starr and Ben Day) – apart from a very interesting topic, the chemistry between the two presenters made for good entertainment (especially their different viewpoints on Bowling – Ten Pin or Candlestick). David and Ben took us on a live ride from the start of a unit test through the cycles of code, test, refactor and showed us a very useful way for developers to stay on top of their game. In fact I was so buzzed I started to use the technique there and then, following David as he walked us through the problem solving exercise. I would highly recommend any serious developer interested in TDD to utilize the technique.

DPR204 | Top 10 Mistakes in Unit Testing

(Ben Day) – Ben covered a topic that was very close to my heart and did not disappoint in the least. In fact not only did he have the 10 mistakes listed, but even provided a further 4 more. Ben’s approach to the topic was very much along the lines of TDD and covered the many pitfalls that people face when embarking on unit testing. Although his ordering was not exactly the same way as I would have perceived it (he did say that they were not in a particular order); he definitely covered the aspects of mistakes made in taking on Unit Testing and showed us some prime examples along with tips on how to avoid the pitfalls.

DEV403 | Building Extensions for the Microsoft Visual Studio Architecture Tools

(Peter Provost) – Peter peeled back the covers on the extensibility of VS 2010 and showed us a glimpse of what is possible with the extensions in the Architecture Tools. Some of the methods by which we can extended the tools varied from the sublime (copying files to a specific folder) to the more subtle and elegant such as writing custom code and deploying them. My only frustration was not to have my MSDN information to hand to be able to download the Feature Pack; however as soon as I am back at the office I shall be trying it out. Combining this session with Mark and Suhails (DEV08-INT) gives a complete picture in to just what we can do with the Architecture tools of VS 2010.

I could go on and on about the sessions that I attended, but the biggest take away from this TechEd is the advancement that Microsoft has made in their Developer tools and how much they have listened to and involved the development community. From the obvious presence of Agile practices in many of the presentations to the technologies and tools available, I was not disappointed by the content and in fact I would go as far as to say – a very grateful thank you from this individual for moving us (in my mind) in the right direction for software development.

  • Share/Bookmark

At long last (On a couple of levels I have to add)!

First and foremost – after a long absence from blogging due to a life-changing event (i.e. recent addition to the family) I have managed to write up an article that has been on my mind since June last year! Secondly, because I finally managed to get the example to work – after months of on and off attempts I had been blocked by a very silly and obvious issue (more later) and this evening I managed to concentrate and see it through.

So what’s the big deal?

My desire was to write a blog explaining the beauty of using POCO from EF 4.0 all the way up through WCF to a client application. I had naively assumed that it would be a straightforward case of building the EFDM, creating my POCO classes, create the appropriate Context Interface (see my earlier blog article on creating an appropriate Context Interface) and then write the WCF service to use the EFDM and expose the same POCO classes to the client – how naïve!

The issue actually came up when I tried to pass the EF “filled” POCO classes back through the WCF service. Bang! I got stumped with the following exception:

System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---

Although I had the WCF Tracing enabled; I couldn’t for the life of me figure out what it was. Finally after digging through fresh traces I read carefully what the buried exception was:

There was an error while trying to serialize parameter http://tempuri.org/:GetDiverResult. The InnerException message was 'Object graph for type 'DiveLogger.Base.DataContracts.DiveProfile' contains cycles and cannot be serialized if reference tracking is disabled.'.  Please see InnerException for more details.

Of course! How silly of me! It was the fact that the navigation properties of my entities were actually causing cyclic references. Now there was a couple of ways I could do this.

  1. Scrutinize my navigation properties and make sure that the return reference properties were made private (this way the XML Serialization of WCF would overlook it as they would be POCO (i.e. no DataContract attributes here!) – it does work as I tried it out for a laugh.
  2. Utilize the blogged “Cyclic References Aware Contract Behavior” derived from IContractBehavior example. This would allow me to pass my POCO class through un-changed and not cause an exception (that would shutdown my service connection unexpectedly).

In the attached code example I have used the second option as I want to try and demonstrate how we can go from Data Model through EF context to the client via a WCF Service, without decorating our class with any special attributes or referencing any EF or Serialization classes – i.e. real to goodness POCO!

As my regular readers will recognize by now that my reason for being so excited about this (apart from the ability to inject interfaces and have my separation of concerns) is for the all important Unit Tests – after all what fun would it be?

The idea of this exercise was to show that with .NET 4.0 we can now release our bonds to specific assemblies / classes and have truly lightweight classes. Consider how pre-4.0 would have been done:

POCO through technology stack

Each layer would have involved some form of transformation from one type to another simply to avoid issues with the associated technology stack.

Consider the “new” way with .NET 4.0:

POCO through technology stack

Now we don’t have to do any transformation from one type to another because the same type is used all the way up the technology stack without any issues (except for the one described earlier).

So how was it done?

The following steps will guide you through the process:

1. Define our POCO classes according to our Data Model:

[POCO classes]

POCO Definition

[Data Model]

EF Data Model

2. Remove the Custom Tool from the DataMapping properties
(so that we can use POCO):

EFDM Custom Tool

Effect of removing EFDM Custom Tool

3. Define the Context Interface that will become the injection point in future references to the DAL:

    public interface IDiveLoggerContext
    {
        IObjectSet AccessTypes { get; }
        IObjectSet CertificationTypes { get; }
        IObjectSet DiveProfiles { get; }
        IObjectSet Divers { get; }
        IObjectSet DiveSites { get; }
        IObjectSet SurfaceTypes { get; }
        IObjectSet WaterBodyTypes { get; }
    }

And implement it

Implement Context Interface

4. In a WCF project define the Service Interface (we will not decorate the DataContracts as they are POCO):

namespace DiveLogger.Service
{
    [ServiceContract]
    public interface ILoggerService
    {
        [OperationContract]
        Diver GetDiver(int id);
    }
}
5. Create the CyclicReferencesAwareContractBehavior, CyclicReferencesAwareAttribute and ApplyCyclicDataContractSerializerOperationBehavior classes as described in Chabsters blog (WCF Cyclic references support). Obviously if there are no cyclic references in any of our entities, then chances are you will not need to put in this workaround for WCF 4.0.

Cyclic Reference Treatment Classes

And use it on the Service contract

Use CyclicReferencesAware attribute

Now the XmlSerialization can handle those pesky cyclic reference Navigation Properties and our WCF Service will work.

6. Utilize the Context Interface we created earlier to separate the DAL from the Service:

    public class LoggerService : ILoggerService
    {
        private IDiveLoggerContext m_context;

        public LoggerService()
        {
            Initialize(null);
        }

        internal LoggerService(IDiveLoggerContext i_context)
        {
            Initialize(i_context);
        }

        private void Initialize(IDiveLoggerContext i_context)
        {
            m_context = i_context ?? new DiveLoggerContext(UtilityFunctions.BuildAdoConnectionString(null));
        }

        public Diver GetDiver(int id)
        {
            if (id < 1 || id > 999)
                throw new ArgumentOutOfRangeException("Diver ID needs to be between 1 and 999", "id");

            IQueryable query = from diver in m_context.Divers
                                      .Include("CertificationTypes")
                                      .Include("DiveProfiles")
                                      .Include("DiveProfiles.DiveSite")
                                      .Include("DiveProfiles.WaterBodyType")
                                      .Include("DiveProfiles.AccessType")
                                      .Include("DiveProfiles.SurfaceType")
                                      where diver.Id == id
                                      select diver;
            Diver retVal = query.ToList().SingleOrDefault();
            return retVal;
        }
    }
7. In our Unit Test we can mock out the Context Interface instead of generating an actual instance:

    [TestMethod]
    public void TestGetSingleDiver()
    {
        // - ARRANGE -
        // Create the stub instance
        IDiveLoggerContext context = MockRepository.GenerateStub();

        // define/create dummy data
        int id = 500;
        string firstName = "Sherlock";
        string lastName = "Holmes";
        string title = "Mr.";
        IObjectSet divers = TestHelper.CreateDivers(id, firstName, lastName).AsObjectSet();

        // declare instance that we want to "retrieve"
        Diver individual;

        // Explicitly state how the stubs should behave
        context.Stub(stub => stub.Divers).Return(divers);

        // Create a real instance of the Servcie that we want to put under test, injecting the dependency in the constructor
        LoggerService service = new LoggerService(context);

        // - ACT -
        individual = service.GetDiver(id);
        // - ASSERT -
        // Make absoultely sure that the expected excption type was thrown
        Assert.IsNotNull(individual);
        // Make sure that the method was NOT called.
        context.AssertWasCalled(stub => { var temp = stub.Divers; });
    }

This will mean that we can get more realistic code-coverage on our Service:

Code Coverage

The following zip file contains all of the classes and code mentioned in the steps outlined previously:

Divelogger.zip

  • Share/Bookmark

Visual Studio 2010 - Beta 2

Whilst preparing for my Entity Framework 4.0 and Unit Testing presentation at the recent New England Code Camp, I came across an issue with my code that I couldn’t entirely understand. Picture the scenario:

In Visual Studio 2008 utilizing EF 1.0:

  • Create a repository Assembly that contains the model and entity classes (i.e. no POCO) for a group of tables in my DB
  • Create a Manager class to expose public functions / methods to retrieve data from the DB via the EntityContext
    [store the Manager.cs file in a common area and create a Link to it from the project].
  • Create an extension method that will handle the usage of Lambda expressions inside the context of .Include() [Did I say I hate "magic strings"?]
    [store the ObjectQueryExtension.cs file in a common area and create a Link to it from the project]
  • Create a simple Console app to call the methods on the Manager class
    [store the Program.cs file in a common area and create a Link to it from the project].

Visual Studio 2008

In Visual Studio 2010 Beta 2 utilizing EF 4.0:

  • Create a repository Assembly that contains the model and entity classes (i.e. no POCO) for a group of tables in my DB
  • Create a Manager class to expose public functions / methods to retrieve data from the DB via the EntityContext
    [create a Link to the Manager.cs file from the project in a common area].
  • Create an extension method that will handle the usage of Lambda expressions inside the context of .Include()
    [create a Link to the ObjectQueryExtension.cs file in the common area from the project]
  • Create a simple Console app to call the methods on the Manager class
    [create a Link to the Program.cs file in the common area from the project].

Visual Studio 2010 - Beta 2

As you will see, the only difference between the two solutions is the actual EntityFramework context definition; one utilizes EF 1.0 and the other EF 4.0.

Compile and execute both and it works perfectly, same Program.cs code for both (making the Console Application); same Manager.cs and ObjectQueryExtension.cs code for both (making the RepositoryManager assembly).

Now the fun starts. I then worked my way back to using Dependency Injection and created the unit test methods based on the VS 2010 project described above. When the compiler attempts to compile the following section of code:


IQueryable<Person> query = context.PersonSet
                               .Include(p => p.PersonalDetail)
                               .Include("FavoriteBeers.Beer")
                               .Include(p => p.Customer.Include<Customer, CustomerType>(c => c.CustomerType))
                               .Include(p => p.Addresses);

The following compile error was the result of the attempted compilation against the preceding code:


Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,53): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,58): error CS0311: The type 'EFWorkshop.Poco.Base.Entities.Customer' cannot be used as type parameter 'TSource' in the generic type or method 'EFWorkshop.Ef.Repository.ObjectQueryExtension.Include<TSource,TPropType>(TSource, System.Linq.Expressions.Expression<System.Func<TSource,TPropType>>)'. There is no implicit reference conversion from 'EFWorkshop.Poco.Base.Entities.Customer' to 'System.Data.Objects.DataClasses.IEntityWithRelationships'.
Ef4.0AndEf1.0\Common\ObjectQueryExtension.cs(118,33): (Related location)
Ef4.0AndEf1.0\PocoInEF4.0\EFWorkshop.Poco.RepositoryManager\Manager.cs(78,60): error CS1061: 'System.Linq.IQueryable<EFWorkshop.Poco.Base.Entities.Person>' does not contain a definition for 'Customer' and no extension method 'Customer' accepting a first argument of type 'System.Linq.IQueryable<EFWorkshop.Poco.Base.Entities.Person>' could be found (are you missing a using directive or an assembly reference?)

However, the following “magic string” laden Includes compile and execute fine:


IQueryable<Person> query = _context.People
    .Include("FavoriteBeers.Beer")
    .Include("PersonalDetail")
    .Include("Customer.CustomerType")
    .Include("Addresses");

Therefore it would seem that the non POCO based classes permit us having the Lambda expression based includes as described earlier; however the moment that POCO is introduced that style of Include is no longer viable – or is it?

  • Share/Bookmark

Wow – June 24th was the last entry! First of all I need to apologize for my bad blogging; I have no other excuse except for the volume of work AT work. Sure I could have re-prioritized and it may have made a difference, but I don’t think my employer would have been very pleased.

So, New England Code Camp, Microsoft Offices, Waltham, MA – full information can be found at http://www.thedevcommunity.org/Events/PresentationList.aspx?id=13. Today I am giving two presentations:

Using Entity Framework’s New POCO Features: Part 2 (Unit Testing)

Level: Intermediate

Starts: Oct 17 2009 2:50 PM

Ends: Sep 17 2009 4:05 PM

Room: MPR A

Speaker: James Phillips

In many cases Unit Testing is considered a chore rather than another development task and often ends up being the last task in a development cycle. More often than not, the sheer work involved in preparing unit tests for existing code can lead to the production of Integration Tests rather than true Unit Tests. Where a unit of code that is under test relies on an external resource, such as a Database or Configuration file, the dependency can lead to testing of the underlying mechanism as well as the unit being tested. This was especially true with Entity Framework 1.0 shipped with .NET Framework 3.5 Service Pack 1. With the advent of .NET Framework 4.0, the Entity Framework has advanced in favor of better Unit Testing with the use of POCO and the ability to create interfaces based on IObjectSet. This presentation will cover the examples that can lead to true Unit Testing as opposed to Integration Testing and provide valuable feedback metrics such as code coverage and automated build time reporting of results.

SCRUM and TFS

Level: Introductory

Starts: Oct 17 2009 4:10 PM

Ends: Sep 17 2009 5:25 PM

Room: Rhode Island

Speaker: James Phillips

SCRUM has grown in popularity and acceptance by many companies over the world with numbers of registered SCRUM Masters reaching 51,955 (11 March 2009 – Jeff Sutherland). Although SCRUM does not stipulate what tools to use to produce the necessary artifacts, Microsoft Team Foundation System provides a number of features via TFS Explorer that facilitate capturing the artifacts of SCRUM and is a useful tool for any SCRUM Master, Team and Product Owner. This presentation will highlight the SCRUM framework and show you practical use of TFS and other tools that facilitate the ceremonies and artifacts of SCRUM.

The slides and code are available for download here:

SCRUM_And_TFS.zip

EF_POCO_And_UnitTesting_slides.zip”

EF_POCO_And_UnitTesting_code.zip

EF_POCO_And_UnitTesting.zip

  • Share/Bookmark

Finally! I’ve been itching to get into the latest incarnation of the EF for a while now and finally I had the opportunity to take it around the block (kick the tires and generally rough it up). My main interest in EF 2.0 was the supposed support for Unit Testing and the improvements on using POCO to map to the Data Model.

I have to admit, although I liked EF 1.0 when I first started using it, one of my biggest bug bears was the fact that you had to “disconnect” your entities before you could really work with them outside the context (no pun intended) of the Entity Framework. I was also quite miffed when I discovered there was no easy way to mock the underlying data layer so I ended up with code like this:


    /// <summary>
    /// Loads a customer instance with the relevant information from the database.
    /// </summary>
    /// <param name="i_customerId">The customerId of the customer data to be retrieved.</param>
    /// <param name="o_customer">The customer instance to be created.</param>
    public void Load(string i_customerId, out Customer o_customer)
    {
        if (string.IsNullOrEmpty(i_customerId))
        {
            throw new ArgumentException("Parameter cannot be null.", "i_customerId");
        }
        int numericVal;
        if (!int.TryParse(i_customerId, out numericVal))
        {
            throw new ArgumentException("Parameter cannot be non-numeric.", "i_customerId");
        }
        if (numericVal < 0 || numericVal > 9999)
        {
            throw new ArgumentOutOfRangeException("i_customerId");
        }

        m_customerRepository.Load(i_customerId, out o_customer);

        if (o_customer != null)
        {
            if (!string.IsNullOrEmpty(o_customer.ContactName) && o_customer.ContactName.Contains(" "))
            {
                o_customer.ContactName = o_customer.ContactName.Trim(' ');
                string[] names = o_customer.ContactName.Split(' ');
                if (names.Length > 1)
                {
                    names[names.Length - 1] = names[names.Length - 1].ToUpper();
                }
                o_customer.ContactName = string.Join(" ", names);
            }
        }
    }

In this case, m_customerRepository is the injected ICustomerRepository instance. When we look at the implementation of the actual data layer class (which does not get tested by the Unit Test, we find that inside the Load method we have the following:


    /// <summary>
    /// Loads a customer instance with the relevant information from the database.
    /// </summary>
    /// <param name="i_customerId">The customerId of the customer data to be retrieved.</param>
    /// <param name="o_customer">The customer instance to be created.</param>
    public void Load(string i_customerId, out BaseCustomer o_customer)
    {
        Customer customer = (CustomerSet.Where(cust => !string.IsNullOrEmpty(cust.CustomerID) &&
                                                       cust.CustomerID == i_customerId)).First();
        if (customer != null)
        {
            o_customer = new BaseCustomer()
                             {
                                 Address = customer.Address,
                                 City = customer.City,
                                 CompanyName = customer.CompanyName,
                                 ContactName = customer.ContactName,
                                 ContactTitle = customer.ContactTitle,
                                 Country = customer.Country,
                                 CustomerID = customer.CustomerID,
                                 Fax = customer.Fax,
                                 Phone = customer.Phone,
                                 PostalCode = customer.PostalCode,
                                 Region = customer.Region
                             };
        }
        else
        {
            o_customer = null;
        }
    }

Not the best way of doing things, that is for sure! In fact it is downright ugly (IMHO). So when I heard that there were improvements to the EF for .NET 4.0, especially in the area of Unit Testing I was curious to say the least. As I delved in deeper I started finding more and more things that made it more attractive to my style of development. For example one of the beauties of EF 2.0 is the fact that you can remove the CustomTool that generates the entity classes that are bound to the data model (through the edmx file). When you do this, you effectively get rid of the code generation for the EF instance that you have loaded in your project. There are some excellent examples (and walkthroughs available) from the ADO.NET Team blog:

POCO in Entity Framework : Part 1 – The Experience (excellent walkthrough on removing the CustomTool)

POCO in Entity Framework : Part 2 – Complex Types, Deferred Loading and Explicit Loading

POCO in Entity Framework : Part 3 – Change Tracking with POCO

So now what? Great! So now I can use my POCO to update the Data Model. But I still hadn’t found out how to do true unit testing with DI and mocking? I was quite flummoxed until I realized (with a helpful pointer from a friend at Microsoft – thanks Jason) that the answer was staring me in the face:

“Can’t you create a mock class that derives from IObjectSet instance yourself, or is there a problem doing that?”

Well yes, I did have a problem with that – it meant that I would have to write more code. I was naively hoping to have something like:


List<Customer> cusList = TestHelper.CreateCustomerList();
IObjectSet<Customer> context = cusList.AsObjectSet();

So I was being lazy… I guess that, with each version of .NET, I had become more and more accustomed to so much being done for me that stumbling across something as “simple” as creating an AsObjectSet() function that was not available was bit of a shock. More so when you look at what IS available on a List<entity> method / property list.

At first I contented myself with just doing what was obvious – create a mock class that inherited from IObjectSet<Customer>, before I realized (with another push from Jason) that I could make it more generic and have a MockObjectSet<T> class:


    internal class MockObjectSet<T> : IObjectSet<T>
        where T : class
    {
        public MockObjectSet(List<T> entityList)
        {
            if (entityList == null)
            {
                throw new ArgumentNullException("entityList");
            }
            else
            {
                _repository = entityList.ToList();
            }
        }

        IList<T> _repository;

        #region IObjectSet<T> Members

        public void AddObject(T entity)
        {
            _repository.Add(entity);
        }

        public void Attach(T entity)
        {
            this.AddObject(entity);
        }

        public void DeleteObject(T entity)
        {
            _repository.Remove(entity);
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            return _repository.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _repository.GetEnumerator();
        }

        #endregion

        #region IQueryable Members

        public Type ElementType
        {
            get { return typeof(T); }
        }

        public System.Linq.Expressions.Expression Expression
        {
            get { return _repository.AsQueryable<T>().Expression; }
        }

        public IQueryProvider Provider
        {
            get { return _repository.AsQueryable<T>().Provider; }
        }

        #endregion
    }

It is important to note here that the TestHelper.CreateCustomerList() function has several overrides and returns a List<Customer> filled with dummy data.

After playing around a bit I realized that I could actually just create an Extension Method that would create an instance of the mock CustomerSet and therefore I could call it from within my Unit Test code. The Extension Method looks like this:


    public static class ObjectSetExtension
    {
        public static IObjectSet<T> AsObjectSet<T>(this List<T> entities) where T : class
        {
            return new MockObjectSet<T>(entities);
        }
    }

Now if we revisit the unit test code, we get the following:


        [TestMethod]
        public void TestLoadValidCustomerContactNameWithSurname()
        {
            // Arrange
            // Create the stub instance
            INorthwindContext context = MockRepository.GenerateStub<INorthwindContext>();
            // Create the dummy data
            const string customerId = "555";
            const string contactName = "James Person";
            IObjectSet<Customer> customers = TestHelper.CreateCustomerList(contactName, customerId).AsObjectSet();

            // declare the dummy instance we are going to use
            Customer loadedCustomer;

            // Explicitly state how the stubs should behave
            context.Stub(stub => stub.Customers).Return(customers);

            // Create a real instance of the CustomerManager that we want to put under test
            Managers.CustomerManager manager = new Managers.CustomerManager(context);

            // Act
            manager.Load(customerId, out loadedCustomer);

            // Assert
            context.AssertWasCalled(stub => { var temp = stub.Customers; });
            // Check the expected nature of the dummy intance
            Assert.IsNotNull(loadedCustomer);
            Assert.IsNotNull(loadedCustomer.ContactName);
            Assert.IsTrue(loadedCustomer.ContactName == "James PERSON");
        }

If we compare the two managers again (the manager that I had created in a previous blog posting depended on EF 1.0), we will see that the EF 2.0 instance actually contains lambda expressions to do the queries.

EF 1.0:


    /// <summary>
    /// Loads a customer instance with the relevant information from the database.
    /// </summary>
    /// <param name="i_customerId">The customerId of the customer data to be retrieved.</param>
    /// <param name="o_customer">The customer instance to be created.</param>
    public void Load(string i_customerId, out Customer o_customer)
    {
        if (string.IsNullOrEmpty(i_customerId))
        {
            throw new ArgumentException("Parameter cannot be null.", "i_customerId");
        }
        int numericVal;
        if (!int.TryParse(i_customerId, out numericVal))
        {
            throw new ArgumentException("Parameter cannot be non-numeric.", "i_customerId");
        }
        if (numericVal < 0 || numericVal > 9999)
        {
            throw new ArgumentOutOfRangeException("i_customerId");
        }

        m_customerRepository.Load(i_customerId, out o_customer);

        if (o_customer != null)
        {
            if (!string.IsNullOrEmpty(o_customer.ContactName) && o_customer.ContactName.Contains(" "))
            {
                o_customer.ContactName = o_customer.ContactName.Trim(' ');
                string[] names = o_customer.ContactName.Split(' ');
                if (names.Length > 1)
                {
                    names[names.Length - 1] = names[names.Length - 1].ToUpper();
                }
                o_customer.ContactName = string.Join(" ", names);
            }
        }
    }

EF 2.0:


    /// <summary>
    /// Loads a customer instance with the relevant information from the database.
    /// </summary>
    /// <param name="i_customerId">The customerId of the customer data to be retrieved.</param>
    /// <param name="o_customer">The customer instance to be created.</param>
    public void Load(string i_customerId, out Customer o_customer)
    {
        if (string.IsNullOrEmpty(i_customerId))
        {
            throw new ArgumentException("Parameter cannot be null.", "i_customerId");
        }
        int numericVal;
        if (!int.TryParse(i_customerId, out numericVal))
        {
            throw new ArgumentException("Parameter cannot be non-numeric.", "i_customerId");
        }
        if (numericVal < 0 || numericVal > 9999)
        {
            throw new ArgumentOutOfRangeException("i_customerId");
        }

        var customers = (from cus in _context.Customers
                         where cus.CustomerID == i_customerId
                         select cus);
        if (customers.Count() == 1)
        {
            o_customer = customers.Single<Customer>();
        }
        else
        {
            o_customer = null;
        }

        if (o_customer != null)
        {
            if (!string.IsNullOrEmpty(o_customer.ContactName) && o_customer.ContactName.Contains(" "))
            {
                o_customer.ContactName = o_customer.ContactName.Trim(' ');
                string[] names = o_customer.ContactName.Split(' ');
                if (names.Length > 1)
                {
                    names[names.Length - 1] = names[names.Length - 1].ToUpper();
                }
                o_customer.ContactName = string.Join(" ", names);
            }
        }
    }

In the second code, snippet, because I am calling straight to an instance of IObjectSet<Customer>, it could either be my mocked one or the actual Entity Framework instance, which looks like this (thanks to POCO binding):


    public class NorthwindContext : ObjectContext, INorthwindContext
    {

        public NorthwindContext()
            : base("name=NorthwindEntities", "NorthwindEntities")
        {
        }

        private ObjectSet<Order> _orders;
        private ObjectSet<Employee> _employees;
        private ObjectSet<Customer> _customers;

        #region INorthwindContext Members

        IObjectSet<Employee> INorthwindContext.Employees
        {
            get { return _employees ?? (_employees = CreateObjectSet<Employee>()); }
        }

        IObjectSet<Customer> INorthwindContext.Customers
        {
            get { return _customers ?? (_customers = CreateObjectSet<Customer>()); }
        }

        IObjectSet<Order> INorthwindContext.Orders
        {
            get { return _orders ?? (_orders = CreateObjectSet<Order>()); }
        }

        #endregion
    }

This means that when I run my code coverage for the EF 2.0 version, I will be hitting the true boundary between the entity and the model, thanks to a combination of POCO and the separation of concerns brought about by IObjectSet.

Ok, so there’s no kitchen sink – what would you do with it if there was?

  • Share/Bookmark

I love these discussions, simply because in most cases, in my opinion, it boils down to personal style. Recently I was discussing with a colleague the different ways a LINQ query could be written for the same result (the discussion was based on code for Entity Framework for .NET 3.5).

Consider the following code snippets; the first uses what has been coined as “Query Comprehension Syntax” and the second is based on Method Chains (also seen referred to as “Extension Methods”):

Query Copmrehension Syntax


var query = (from e in EmployeeSet
             from o in OrderSet
             from c in CustomerSet
             where e.EmployeeID == o.Employees.EmployeeID &&
                   o.Customers.CustomerID == c.CustomerID
             group e by new { EmployeeInstance = e, CustomerInstance = c } into result
             orderby result.Key.EmployeeInstance.LastName
             select result);

Method Chain (Extension Method) Syntax


var query = (EmployeeSet
    .SelectMany(e => OrderSet, (e, o) => new {e, o})
    .SelectMany(@t => CustomerSet,(@t, c) => new {@t, c})
    .Where(@t => @t.@t.e.EmployeeID == @t.@t.o.Employees.EmployeeID &&
                @t.@t.o.Customers.CustomerID == @t.c.CustomerID)
    .GroupBy(@t => new {EmployeeInstance = @t.@t.e, CustomerInstance = @t.c}, @t => @t.@t.e)
    .OrderBy(result => result.Key.EmployeeInstance.LastName));

Well? What is the difference?

In both cases they are trying to emulate the following SQL (albeit with a bit more beef – i.e. returning the complete entities – not just the strings):

[code lang="sql"]

select e.FirstName, e.LastName, c.ContactName
from Customers c, Employees e, Orders o
where e.EmployeeID = o.EmployeeID
and o.CustomerID = c.CustomerID
group by e.FirstName, e.LastName, c.ContactName
order by e.LastName

Ok. What is the difference?

Looking at the output we get the exact same result in both cases (when put through the following algorithm):


Dictionary<BaseEmployee, List<BaseCustomer>> retVal = new Dictionary<BaseEmployee, List<BaseCustomer>>();
string previousEmployeeName = string.Empty;
BaseEmployee previousEmployeeInstance = null;
foreach (var queryItem in query)
{
    BaseEmployee employee = ConvertToBase(queryItem.Key.EmployeeInstance);
    string currentEmployeeName = string.Format("{0}-{1}", employee.FirstName, employee.LastName);
    BaseCustomer customer = ConvertToBase(queryItem.Key.CustomerInstance);
    if (currentEmployeeName != previousEmployeeName)
    {
        previousEmployeeName = currentEmployeeName;
        retVal.Add(employee, new List<BaseCustomer>());
        previousEmployeeInstance = employee;
    }
    retVal[previousEmployeeInstance].Add(customer);
}

So? What is the difference?

And looking at it through SQL Profiler, guess what? That's right! We get exactly the same result - SQL is exactly the same!

Alright already! WHAT IS THE DIFFERENCE?

Really? It would appear to be - readability... In cases where the query is long and drawn out, most of us would be quite comfortable with the QCS format as it is closer to what we are accustomed to seeing in T-SQL; however the Method Chain (Extension Methods) format is much more compact for smaller queries - much neater in my mind.

The whole discussion came about because of the functionality of ReSharper to build the Method Chain. If you hover over a QCS LINQ query, the ReSharper "lightbulb" will appear to give you the following option:

ReSharper Convert To Methods Chain

And VOILA! You have now converted it to a Method Chain... the only gotcha is that you can't change it back (forgetting the use of CTRL + Z).

Similar discussions have appeared here and here on Stack Overflow.

<Update June 10, 2009>:I wrapped some timing around both syntaxes and this was the result:

First time run:

ExtensionMethod syntax: 00:00:01.0271109
QueryComprehensionSyntax syntax: 00:00:01.0216957

Subsequent runs

ExtensionMethod syntax: 00:00:00.0976207
QueryComprehensionSyntax syntax: 00:00:00.0917982
ExtensionMethod syntax: 00:00:00.0955029
QueryComprehensionSyntax syntax: 00:00:00.0908081
ExtensionMethod syntax: 00:00:00.0974213
QueryComprehensionSyntax syntax: 00:00:00.0970167
ExtensionMethod syntax: 00:00:00.0905830
QueryComprehensionSyntax syntax: 00:00:00.1007809
ExtensionMethod syntax: 00:00:00.0895348
QueryComprehensionSyntax syntax: 00:00:00.0965262
ExtensionMethod syntax: 00:00:00.0972316
QueryComprehensionSyntax syntax: 00:00:00.0886347
ExtensionMethod syntax: 00:00:00.1030211
QueryComprehensionSyntax syntax: 00:00:00.0927539
ExtensionMethod syntax: 00:00:00.0943354
QueryComprehensionSyntax syntax: 00:00:00.0919315
ExtensionMethod syntax: 00:00:00.0938015
QueryComprehensionSyntax syntax: 00:00:00.0908355
ExtensionMethod syntax: 00:00:00.0921636
QueryComprehensionSyntax syntax: 00:00:00.0972665

  • Share/Bookmark

Recently a colleague pointed out that my unit test were not following the AAA (Arrange, Act and Assert) structure that they had become accustomed to seeing and as they had understood Unit Tests should be. Although I had argued the point that there were many ways to setup and execute the test I can understand where the confusion can come in when mocking with Rhino Mocks.

I’m an advocate of using what comes natural to you as long as the outcomes are consistent; however I accept that there needs to be some uniformity when working in a team for the simple case of a collective understanding – as long as it is not at the behest of an individual’s ego.

The primary issue boiled down to the difference between the way that the test was prepared in my original blog posting:


[TestMethod]
public void TestInsertValidCustomerContactNameWithSurname()
{
    // Create the mock instance
    ICustomerRepository customerRepository = m_mockRepository.DynamicMock<ICustomerRepository>();

    Customer newEntry = TestHelper.CreateCustomer("James Person");

    // Now we set our expectations - when a null is passed the underlying method should throw an exception
    Expect.Call(() => customerRepository.Insert(newEntry)).Constraints(Property.Value("ContactName", "James PERSON"));

    // Replay our expectations
    m_mockRepository.ReplayAll();

    // Create a real instance of the CustomerManager that we want to put under test
    Managers.CustomerManager manager = new Managers.CustomerManager(customerRepository);

    manager.Insert(newEntry);
}

And setting it up in a true AAA sense:


[TestMethod]
public void TestInsertValidCustomerContactNameWithSurname()
{
    // Arrange
    // Create the stub instance
    ICustomerRepository customerRepository = MockRepository.GenerateStub<ICustomerRepository>();

    // Create the dummy instance to be used as a parameter
    Customer newEntry = TestHelper.CreateCustomer("James Person");

    // Create a real instance of the CustomerManager that we want to put under test
    Managers.CustomerManager manager = new Managers.CustomerManager(customerRepository);

    // Act
    manager.Insert(newEntry);

    // Assert - here we also check the property value ContactName to make sure that it is as expected.
    customerRepository.AssertWasCalled(stub => stub.Insert(newEntry), stub => stub.Constraints(Property.Value("ContactName", "James PERSON")));
}

Notice how the second example shows very distinct Arrange, Act and Assert structure.

Both methodologies result in the same outcome and at the end of the day I would say that you should use what works for you – as long as other people can understand the logic (“What if you should get hit by a bus?”).

  • Share/Bookmark

One way to use the Entity Framework on your legacy code

Following on the DI blog posts that I have been authoring lately, I wanted to discuss one possible method of stripping out the underlying data access layer (DAL) and introduce the Entity Framework from Microsoft. My intention is to write about how you would be able to use DI when introducing the new DAL.

Starting with what we already have.

In many cases there will be some form of data access layer manager class that will act as the proxy to client code when performing the request to the database and translating the returned query into “code entities”. This would be the ideal place to start the transition (obviously). Capitalizing on our earlier example of the NorthWind database, let’s assume that we have the following classes:

Base Classes

As you will see, we have two DAL related classes; EmployeeRepository and CustomerRepository. Both of these expose typical CRUD methods that we will refactor into interfaces. Once the principal methods have been extracted into interfaces then we can create the new client facing entities that will provide access to the DAL via the appropriate methods and functions:

Manager Classes

As you can see from the class diagram, each of the manager classes has two constructors; the first (parameter-less) constructor is the default and contains no code except for calling into the second constructor; the second (single parameter) constructor contains the assignation of a member variable to the associated repository interface:

  1. /// <summary>
  2.     /// Parameterless (Default) constructor
  3.     /// </summary>
  4.     public EmployeeDataManager() : this(null)
  5.     {
  6.     }
  7.  
  8.     /// <summary>
  9.     /// Parameterized constructor
  10.     /// </summary>
  11.     /// <param name="i_repository">The IEmployeeRepository instance to
  12.     /// be used.</param>
  13.     internal EmployeeDataManager(IEmployeeRepository i_repository)
  14.     {
  15.         m_repository = i_repository;
  16.     }

One important note to make and something that may or may not seem strange is the definition of the second constructor as internal as opposed to public. If you remember from a previous post, by defining the second constructor as internal and then exposing it only to the unit tests (via the assembly attribute InternalsVisibleTo) – this way when coding the clients of the manager, we will not place the onus of instantiating a repository on the client (unless you wish to do so).

Later on, once we have the DAL utilizing the Entity Framework in place, we can extend the assignation of the repository interface to also include the instantiation of our default DAL.

Incorporating the Entity Framework

The first stage is to create a suitable assembly where the Entity Framework related classes will reside and be referenced from. Therefore we could create an entity access assembly:

Pre Entity Framework

Now we can go through the steps of incorporating the Entity Framework:

  1. In the EntityAccess project, add a new “ADO.Net Entity Data Model” item:

    Stage 1
  2. In this example we want to create the model contents from the actual DB instance:

    Stage 2
  3. The next window of the Entity Data Model Wizard specifies the Data Connection that will be used. Depending on your requirements this will vary from situation to situation:

    Stage 3
  4. In this case we will create a new one for our purposes; click the “New Connection…” button to display the Connection Properties dialog (Fill-out the fields as appropriate to your purposes) and select the Server and the Database instance:

    Stage 4
  5. Once the Connection Properties have been configured, the appropriate information will appear:

    Stage 5
  6. Clicking the “Next >” button will take us to the “Choose Your Database Objects” window, where we can select the tables that we are interested in (seeing as it is such a small schema, we will select all tables in this example):
    Stage 6
  7. Once we have clicked on the “Finish” button the associated edmx file (XML file that defines an Entity Data Model) and it’s associated code behind have been generated:
    Stage 7 - a


    Test Stubs Dialog
  8. For consistency reasons (and personal preference) I normally change the default entity naming convention as follows, renaming the pluralized to singular:
    Stage 8 - a

    becomes

    Stage 8 - b


    Stage 8 - c

Now that we have added the Entity Framework into the solution we can set about incorporating the use of the appropriate repository interfaces (ICustomerRepository and IEmplyeeRepository).

Delving into the code generated when the Entity Data Model was generated (NorthWind.Designer.cs) we find that the class is defined as partial:

  1. /// <summary>
  2.     /// There are no comments for NorthwindSQLEntities in the schema.
  3.     /// </summary>
  4.     public partial class NorthwindSQLEntities : global::System.Data.Objects.ObjectContext
  5.     {
  6.      …
  7.     }

This means that we could use the same class to implement the two interfaces we already have defined:

Stage 9 - a

Unfortunately when we attempt this method of implementing the repository interfaces we encounter the following error on the first attempt at accessing the database via the entity data model:

Stage 9 - b

With this issue raised it is easier to sub-class the Entity Data Model generated class and implement the interfaces in the child class:

Stage 9 - c

Further digging around in the auto-generated Entity Data Model reveals the different overloads for the constructor:

  1. /// <summary>
  2.     /// Initializes a new NorthwindSQLEntities object using the
  3.     /// connection string found in the ‘NorthwindSQLEntities’ section
  4.     /// of the application configuration file.
  5.     /// </summary>
  6.     public NorthwindSQLEntities() :
  7.             base("name=NorthwindSQLEntities", "NorthwindSQLEntities")
  8.     {
  9.         this.OnContextCreated();
  10.     }
  11.     /// <summary>
  12.     /// Initialize a new NorthwindSQLEntities object.
  13.     /// </summary>
  14.     public NorthwindSQLEntities(string connectionString) :
  15.             base(connectionString, "NorthwindSQLEntities")
  16.     {
  17.         this.OnContextCreated();
  18.     }
  19.     /// <summary>
  20.     /// Initialize a new NorthwindSQLEntities object.
  21.     /// </summary>
  22.     public NorthwindSQLEntities(global::System.Data.EntityClient.EntityConnection connection) :
  23.             base(connection, "NorthwindSQLEntities")
  24.     {
  25.         this.OnContextCreated();
  26.     }

With this in mind we can create a constructor that takes 4 parameters that can be used to generate the appropriate connection string:

  1. /// <summary>
  2.     /// Creates a new NorthwindEntityContext.
  3.     /// This class will be the handler for all CRUD operations
  4.     /// perfomed by the EntityAccess layer.
  5.     /// A connection is created from this constructor.
  6.     /// </summary>
  7.     public NorthwindSQLEntities(
  8.         string i_serverName,
  9.         string i_catalogName,
  10.         string i_user,
  11.         string i_pswd)
  12.             : base(BuildConnectionString(
  13.                 i_serverName,
  14.                 i_catalogName,
  15.                 i_user,
  16.                 i_pswd))
  17.         {
  18.            
  19.         }

The BuildConnectionString function would construct the appropriate connection string as follows:

  1. private static string BuildConnectionString(string i_serverName, string i_catalogName, string i_user, string i_pswd)
  2.     {
  3.         string serverName = Environment.MachineName;
  4.         if (!string.IsNullOrEmpty(i_serverName))
  5.             serverName = i_serverName;
  6.         string catalogName = "NorthwindSQL";
  7.         if (!string.IsNullOrEmpty(i_catalogName))
  8.             catalogName = i_catalogName;
  9.  
  10.         string AdoConnectionString = string.Empty;
  11.         if (!string.IsNullOrEmpty(i_user))
  12.         {
  13.             AdoConnectionString = string.Format(
  14.             "Data Source={0};Initial Catalog={1};Integrated Security=False;MultipleActiveResultSets=True;Uid={2};Pwd={3}",
  15.             serverName, catalogName, i_user, i_pswd);
  16.         }
  17.         else
  18.         {
  19.             AdoConnectionString = string.Format(
  20.                 "Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=True",
  21.                 serverName, catalogName);
  22.         }
  23.         return string.Format(
  24.             "metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl;provider=System.Data.SqlClient;provider connection string=\";{1}\";",
  25.             EntityModelName, AdoConnectionString);
  26.     }

The Entity Framework provides the appropriate mapping between the Storage Model (Database) and the Conceptual Model (entities), however, in order to be able to implement Dependency Injection we need to maintain (or create) a disconnected set of implementation classes that are agnostic to the underlying repository (be it Entity Framework or any other data access model, such as NHibernate, etc.).

Therefore the CRUD methods that we have exposed through our original interfaces, in the Entity Framework domain, would provide a certain amount of “translation” from the disconnected entity type to the “connected” (EDM) type:

  1. using BaseCustomer = DiDemo.BaseData.Entities.Customer;
  2. using DiDemo.BaseData.Interfaces;
  3.  
  4. namespace DiDemo.EntityAccess
  5. {
  6.     public partial class NorthwindSQLEntities :
  7.         ICustomerRepository, IEmployeeRepository
  8.     {
  9.     /// <summary>
  10.     /// Insert a new Customer instance into the Database.
  11.     /// </summary>
  12.     /// <param name="i_customer">
  13.     /// The Customer instance to be inserted.
  14.     /// </param>
  15.     public void Insert(BaseCustomer i_customer)
  16.     {
  17.         Customer customer = new Customer()
  18.             {
  19.                 Address = i_customer.Address,
  20.                 City = i_customer.City,
  21.                 CompanyName = i_customer.CompanyName,
  22.                 ContactName = i_customer.ContactName,
  23.                 ContactTitle = i_customer.ContactTitle,
  24.                 Country = i_customer.Country,
  25.                 CustomerID = i_customer.CustomerID,
  26.                 Fax = i_customer.Fax,
  27.                 Orders = new EntityCollection<Order>(),
  28.                 Phone = i_customer.Phone,
  29.                 PostalCode = i_customer.PostalCode,
  30.                 Region = i_customer.Region
  31.             };
  32.         this.AddToCustomerSet(customer);
  33.         this.SaveChanges();
  34.     }

Unit Testing

Now that we have the underlying Data Access Layer sorted out, time to move on to the reason for this blog posting – Unit Testing.

Obviously the very basic CRUD methods and functions do not provide any head banging issues when it comes to unit testing, however, suppose there a function returned an IQueryable instance? It could possibly be conceived that such a method existed as follows:

  1. /// <summary>
  2.     /// Returns a List of Customer instances
  3.     /// </summary>
  4.     /// <returns>List containing all Customer instances.</returns>
  5.     public List<BaseCustomer> LoadAllCustomers()
  6.     {
  7.         return Query_LoadAllCustomers().ToList();
  8.     }
  9.  
  10.     /// <summary>
  11.     /// Returns an IQueryable for the Customers entity set.
  12.     /// </summary>
  13.     /// <returns>IQueryable of the customer enitity set.</returns>
  14.     public IQueryable<BaseCustomer> Query_LoadAllCustomers()
  15.     {
  16.         return (from query in CustomerSet
  17.                 select new BaseCustomer()
  18.                 {
  19.                     Address = query.Address,
  20.                     City = query.City,
  21.                     CompanyName = query.CompanyName,
  22.                     ContactName = query.ContactName,
  23.                     ContactTitle = query.ContactTitle,
  24.                     Country = query.Country,
  25.                     CustomerID = query.CustomerID,
  26.                     Fax = query.Fax,
  27.                     Phone = query.Phone,
  28.                     PostalCode = query.PostalCode,
  29.                     Region = query.Region
  30.                 });
  31.     }

Surprisingly enough it is not that difficult to create the unit test for such a method in the Manager class. Seeing as we have successfully done the dependency injection prior to creating the entity framework related classes, all we are actually doing is writing the test for the manager class by mocking the repository interface:

  1. [TestMethod]
  2.     public void TestIQueryableOnEntity()
  3.     {
  4.         // Create the mock instance
  5.         IEmployeeRepository eConnect = m_mockRepository.DynamicMock<IEmployeeRepository>();
  6.  
  7.         // Here we create an actual instance
  8.         IQueryable<Employee> mockedCollection;
  9.  
  10.         // Setup a dummy list that will be filtered, queried, etc
  11.         List<Employee> employeeList = CreateEmployeList();
  12.         mockedCollection = employeeList.AsQueryable();
  13.  
  14.         // Now we set our expectations
  15.         Expect.Call(eConnect.Query_LoadAllEmployees()).Return(mockedCollection);
  16.  
  17.         // Replay our expectations
  18.         m_mockRepository.ReplayAll();
  19.  
  20.         // Create a real instance of the EmloyeeConnector that we want to put under test
  21.         EmployeeManager manager = new EmployeeManager(eConnect);
  22.  
  23.         List<Employee> employees = manager.Query_LoadAllEmployees().ToList();
  24.  
  25.         Assert.IsNotNull(employees);
  26.  
  27.         Assert.IsTrue(employees.Count == employeeList.Count);
  28.     }

The secret is in the AsQueryable method on the List instance. By doing this we can simulate the behavior of the IQueryable function on our Entity Data Model.

  • Share/Bookmark