# Sunday, May 22, 2011

Last weekend I presented a session at the third annual Chicago Code Camp entitled: Test-driven Development in .NET – Tips, Tools, and Techniques.  The session was standing room only and carried into the commons area afterwards with some excellent questions from attendees.  What is greater than that is that the questions didn’t stop there, they kept coming via email.  One question in particular has stuck with me because it was a hurdle I myself had to overcome early on in my TDD adventures.

The question boiled down to how do you test code the depends on ASP.NET, specifically Web Configuration and Application Settings?  So I thought I would put together a blog post how this can be done, and how it should be done.

To set the stage…I have a simple ASP.NET web application with one page and one class.  The page load method calls the one method in the class that returns an app setting stored in the web config file.

  1. namespace WebApp
  2. {
  3.     public partial class Index : System.Web.UI.Page
  4.     {
  5.         protected void Page_Load(object sender, EventArgs e) {
  6.             lblValue.Text = SomeClassThatNeedsTesting.GetSomeStringValue();
  7.         }
  8.     }
  9. }

  1. namespace WebApp
  2. {
  3.     public static class SomeClassThatNeedsTesting
  4.     {
  5.         public static string GetSomeStringValue() {
  6.             return System.Web.Configuration.WebConfigurationManager.AppSettings["MyAppSettingValue"];
  7.         }
  8.     }
  9. }

Your first option to getting your tests to run and return the configuration and/or app settings is to tell your tests to run under the ASP.NET host process and not the VSTest host process and also tell what url to run the test under.

  1. [TestMethod]
  2. [HostType("ASP.NET")]
  3. [UrlToTest("http://localhost:2356/Index.aspx")]
  4. [AspNetDevelopmentServerHost("$(SolutionDir)\\WebApp")]
  5. public void GetSomeStringValue_ShouldReturn_NonNull_NonEmpty_String() {
  6.     var val = WebApp.SomeClassThatNeedsTesting.GetSomeStringValue();
  7.     Console.WriteLine(val.ToString());
  8.     Assert.IsFalse(string.IsNullOrEmpty(val));
  9. }

If you run this you will see that the test passes…eventually…after Casini is started and the test runner twiddles its thumbs for a bit.  Speed is my first issue with setting up your test to run in this fashion.  My second issue is that you aren’t testing the ASP.NET configuration framework so why would you need to add all this extra plumbing to make your code take that route?  There is a better option!

Since we really don’t care how or where are value comes from we just need some sort of value returned so we can test our method, we can easily add a thin layer of abstraction and mock the pieces of code that depend on ASP.NET.

Lets start by creating an interface for a simple class that reads application settings.

  2. namespace WebApp {
  4.     public interface IAppSettingsReader {
  6.         string GetAppSettingValue(string settingKey);
  7.     }
  8. }

Now we can implement the interface and add the actual code to read the app settings from the web config file.

  1. namespace WebApp {
  3.     public class AppSettingsReader : IAppSettingsReader {
  5.         public string GetAppSettingValue(string settingKey) {
  6.             if (string.IsNullOrEmpty(settingKey)) throw new NullReferenceException("settingKey is required");
  7.             return (WebConfigurationManager.AppSettings[settingKey]);
  8.         }
  10.     }
  11. }

Next we will modify our class that needs testing to use the new AppSettingsReader.  Because our goal is to eventually be able to mock the settings reader we need to invert the control of the dependency and provide a mechanism for injecting the dependency.  The change is fairly straightforward.

  1. namespace WebApp {
  3.     public class SomeClassThatNeedsTesting {
  5.         private readonly IAppSettingsReader _settingsReader;
  7.         public SomeClassThatNeedsTesting(IAppSettingsReader settingsReader) {
  8.             _settingsReader = settingsReader;
  9.         }
  11.         public string GetSomeStringValue() {
  12.             return _settingsReader.GetAppSettingValue("MyAppSettingValue");
  13.         }
  14.     }
  15. }

Now we have introduced a breaking change and need to modify our page and our test to accommodate the change to SomeClassThatNeedsTesting.

  1. namespace WebApp {
  3.     public partial class Index : Page {
  5.         protected void Page_Load(object sender, EventArgs e) {
  6.             var someClass = new SomeClassThatNeedsTesting(new AppSettingsReader());
  7.             lblValue.Text = someClass.GetSomeStringValue();
  8.         }
  9.     }
  10. }

  1. namespace TestProject {
  3.     [TestClass]
  4.     public class SomeClassThatNeedsTesting_Tests {
  6.         [TestMethod]
  7.         [HostType("ASP.NET")]
  8.         [UrlToTest("http://localhost:2356/Index.aspx")]
  9.         [AspNetDevelopmentServerHost("$(SolutionDir)\\WebApp")]
  10.         public void GetSomeStringValue_ShouldReturn_NonNull_NonEmpty_String_ASP() {
  11.             SomeClassThatNeedsTesting someClass = new SomeClassThatNeedsTesting(new AppSettingsReader());
  12.             string val = someClass.GetSomeStringValue();
  13.             Console.WriteLine(val);
  14.             Assert.IsFalse(string.IsNullOrEmpty(val));
  15.         }
  16.     }
  17. }

At this point we can run our test from above and, after we have taken a bathroom break, checked Twitter, and made a sandwich, we will notice that the test still passes.  This is true because all we have done is add a layer of abstraction.  We have not changed the core functionality of the process.  Now that the layer of abstraction is in place we can write another test and this time instead of writing more code to please ASP.NET lets drop that dependency completely by mocking it.

To implement our mock I am going to use my mocking tool of choice, RhinoMocks.  (I am purposefully not supplying a URL here because you should be using NuGet to get your packages!)

Here is our new and improved test.

New And Improved Test
  1. [TestMethod]
  2. public void GetSomeSringValue_ShouldReturn_NonNull_NonEmpty_String_Mocked() {
  3.     //Arrange
  4.     string myAppSettingValue = "This is my expected mocked setting value";
  5.     MockRepository _repository = new MockRepository();
  6.     IAppSettingsReader mockSettingsReader = MockRepository.GenerateStrictMock<IAppSettingsReader>();
  7.     mockSettingsReader.Expect(msr => msr.GetAppSettingValue("MyAppSettingValue")).Return(myAppSettingValue).Repeat.Once();
  8.     _repository.ReplayAll();
  9.     //Act
  10.     SomeClassThatNeedsTesting someClass = new SomeClassThatNeedsTesting(mockSettingsReader);
  11.     string val = someClass.GetSomeStringValue();
  12.     //Assert
  13.     Assert.AreEqual(myAppSettingValue, val, "Wrong value returned from GetSomeSringValue");
  14. }

If you take a look at the test you can see that the first thing that I did was create my mock AppSettingReader and set my expectations.  After that I instantiated my class under test and passed in the settings reader mock.

Hope you found this useful!  Complete code is available here!

posted on Sunday, May 22, 2011 7:17:23 PM (Central Daylight Time, UTC-05:00)  #    Comments [0]
# Saturday, April 02, 2011

Unit testing certainly does give you the developer a warm fuzzy but that warm fuzzy can only get you so far.  In the end you still have to make sure all your little pieces of code/functionality play nice together.  This requires integration testing and if we are going to do any sort of testing that we actually expect to be performed on a regular basis we have to automate it.  Automated integration testing often gets neglected and is substituted with manual testing, which delays finding issues and adds time to the project timeline.  The reason that integration testing is often neglected is that it requires touching actual data. 

Why is this is an issue:

  1. Someone has to take the time create the data for the testing.
  2. The data has to be reset after each test run

All of this requires a lot of work, coordination…and a DBA [cringe]!

Let me introduce a scenario where all that is not required.  Why can’t we wrap our tests in a Transaction?

Here’s what I am thinking:

  1. Have a local empty copy of the database.
  2. Either in a test-by-test basis or test-suite basis
    1. Start a transaction (either at the start of your test or on build-up of the test suite)
    2. Create your data and put it in the DB
    3. Perform your tests on the data you just created and inserted
    4. Rollback the transaction
  3. … And Repeat

Here is an example:

  1.         [TestMethod]
  2.         public void GetAllEligible_ShouldReturn_All_Attendess_InThe_Database_Where_IsEligible_Equals_True() {
  3.             using (new TransactionScope()) {
  4.                 //Arrange
  5.                 int expectedCount = 1;
  6.                 Attendee attendee1 = new Attendee {FirstName = "Joe", LastName = "Smith", IsEligible = true};
  7.                 Attendee attendee2 = new Attendee {FirstName = "Randy", LastName = "Jones", IsEligible = false};
  8.                 using (var dc = new DayOfDotNetDataContext()) {
  9.                     dc.Attendees.InsertAllOnSubmit(new List<Attendee> {attendee1, attendee2});
  10.                     dc.SubmitChanges();
  11.                 }
  12.                 //Act
  13.                 IAttendeeRepository attendeeRepository = new AttendeeRepository();
  14.                 IList<AttendeeDTO> attendees = attendeeRepository.GetAllEligible();
  15.                 //Assert
  16.                 attendees.Count.ShouldEqual(expectedCount, "Wrong number of attendess");
  17.             }
  18.         }

You can see that the first line of my test starts a transaction scope.  I then create some data and add it to my empty database.  Now, remember this database needs to be empty as to not mess up your expectations.  After the data has been created I then perform the operation I am testing and assert the results.

You may be confused by the lack of a “Rollback” statement.  The way TransactionScope works is that it only commits when explicitly told to do so.

Automated integration testing is a must have and in order to make your life easier follow the steps I have outlined and you will be free to live the TDD dream!

posted on Saturday, April 02, 2011 2:19:41 PM (Central Standard Time, UTC-06:00)  #    Comments [4]
# Friday, December 17, 2010

As I have stated in previous posts I am huge supporter of TDD and you can’t get too far doing true TDD before you are forced to introduce an IoC Container, also known as a Dependency Injection Container.  You can find out more about Inversion of Control and Dependency Injection here.  When I first started looking into using the concept of Inversion Of Control in my code, my first stop was StructureMap.  Why…I can’t really remember but it was the first IoC framework I tried and it is the one I currently prefer to use.  But, being a consultant I pride myself in knowing my options and being able to work with or recommend the tool that is best suited for the situation…hence this blog post and example code.  I decided to put together this post and code showing how, if you plan accordingly, you can swap out any of the *major* IoC Frameworks without impacting the code. 

I set out with the goal of creating a swappable solution that would allow me work with the following IoC Frameworks.

Side Note:  Using NuGet really makes pulling down tools/packages very easy.  Check It Out!

So, let’s get started!  The basic principals of setting up and using an IoC container in code are the same no matter what Container you are using.  From the 30,000 foot view you need to:

  1. Map what concrete class implementations to use for what abstract (interface, abstract class) implementations.
  2. Have some way of resolving to a concrete implementation when passed an abstract implementation.

To get the juices flowing here is how you tackle this in StructureMap.

  1. Create a class that will be called on when our app spins up that will take care of our abstract –> concrete mappings.  Typically this class is called a Bootstrapper.  As you can see this class contains when method called Bootstrap that performs the mapping.  In this example there is one mapping that says (see line 18) whenever you need a concrete instance of IMyBusinessClass use the MyBusinessClass class.
    1. using ChoosingAnIoC.Business;
    2. using ChoosingAnIoC.Core.Interfaces.Business;
    3. using StructureMap;
    5. namespace ChoosingAnIoC.App.Bootsrappers {
    7.     /// <summary>
    8.     /// Maps Abstract to Concrete Implementations Using StructureMap
    9.     /// </summary>
    10.     public class StructureMapBootstrapper : IBootstrapper {
    12.         #region IBootstrapper Members
    14.         /// <summary>
    15.         /// Setup of mappings
    16.         /// </summary>
    17.         public void Bootstrap() {
    18.             ObjectFactory.Initialize(x => x.For<IMyBusinessClass>().Use<MyBusinessClass>());
    19.         }
    21.         #endregion
    22.     }
    23. }


  1. Create a class that can use the IoC containers mappings to hand you a concrete instance of class on demand.  I call this class a Resolver.
    1. using ChoosingAnIoC.Core.Interfaces;
    2. using StructureMap;
    4. namespace ChoosingAnIoC.Core.DependencyResolvers
    5. {
    6.     /// <summary>
    7.     /// Class for resolving dependency's using StructureMap
    8.     /// </summary>
    9.     public class StructureMapDependencyResolver : IDependencyResolver
    10.     {
    11.         /// <summary>
    12.         /// Returns a concrete instance of the
    13.         /// supplied Interface
    14.         /// </summary>
    15.         /// <typeparam name="T">Interface of concrete instance to return</typeparam>
    16.         /// <returns>Concrete instance of the supplied interface</returns>
    17.         public T GetConcreteInstanceOf<T>() {
    18.             return ObjectFactory.GetInstance<T>();
    19.         }
    20.     }
    21. }

If  we add enough level of abstraction at these two points we can swap out any of the current IoC containers and hopefully be able to handle any that come along in the future.  As you probably noticed in the two code examples above…both of these classes implement an interface.  Below is the code for the two interfaces.

      1. namespace ChoosingAnIoC.App.Bootsrappers {
      3.     /// <summary>
      4.     /// Bootsrapper Interface
      5.     /// </summary>
      6.     public interface IBootstrapper {
      8.         /// <summary>
      9.         /// Bootstrap and perform mappings
      10.         /// </summary>
      11.         void Bootstrap();
      12.     }
      13. }
      1. namespace ChoosingAnIoC.Core.Interfaces {
      3.     /// <summary>
      4.     /// Interface for implementations of Dependency Resolver
      5.     /// <remarks>
      6.     /// This interface adds a layer of abstraction when we
      7.     /// resolve dependencies.  It will allow us to swap out
      8.     /// out IoC framework with minimal impact on our code.
      9.     /// </remarks>
      10.     /// </summary>
      11.     public interface IDependencyResolver {
      13.         /// <summary>
      14.         /// Returns a concrete instance of the
      15.         /// supplied Interface
      16.         /// </summary>
      17.         /// <typeparam name="T">Interface of concrete instance to return</typeparam>
      18.         /// <returns>Concrete instance of the supplied interface</returns>
      19.         T GetConcreteInstanceOf<T>();
      21.     }
      22. }

                                    Use this code a couple of factory classes to return whatever Bootstrapper and DependencyResolver our application is configured to use we can swap out IoC containers without affecting our code.

                                    The complete code including implementations of all the IoC containers noted above can be found here!

                                    posted on Friday, December 17, 2010 11:06:46 AM (Central Standard Time, UTC-06:00)  #    Comments [3]
                                    # Sunday, November 14, 2010

                                    I have done a couple of presentations lately on IronRuby and I am now making the slides and demo code available.  Enjoy!


                                    posted on Sunday, November 14, 2010 6:54:00 PM (Central Standard Time, UTC-06:00)  #    Comments [2]
                                    # Friday, October 22, 2010

                                    At my current client I was tasked with implementing coding standards and styles and developing a process so the configurations can be easily maintained and shared.  ReSharper was already in place at the client and the since 99% of what they wanted to enforce, initially at least, was style related I chose to combine ReSharper with StyleCop.

                                    After looking around the interwebs for awhile I realized this process is either impossible or undocumented…or both.

                                    The process I came up with is about 90% of what I was hoping and still requires two manual steps by the developer but overall it is solid.  So, let’s get started.  First download and install the following tools:

                                    1. StyleCop 
                                    2. StyleCop+

                                    Although StyleCop+ is technically not required it does a great job with allowing you to extend and customize a lot of the built in StyleCop rules.  So I certainly recommend it.

                                    The trick with StyleCop is that it will continue to look up the code tree for settings files and keep adding them together and then adds the settings file from StyleCop install directory to top things off.  That is unless you tell it to do otherwise.  What where going to do is first place a Settings.StyleCop file where all devlopers can access it.  Next we are going to place another at the root of our code directory.  So if your code resides at C:\Dev\Code then place the Settings.StyleCop file there.  We can then open up the settings file we placed out on the network that everyone has access to and tell it not to merge with any other settings file.  This will be the official settings file.


                                    Next we will open the settings file in the root of our source tree and tell it merge only with the settings in the shared location.


                                    Now once you make changes at the shared level they will be merged with each developers settings file.

                                    Next we can deal with ReSharper…Stay Tuned!

                                    posted on Friday, October 22, 2010 4:19:52 PM (Central Daylight Time, UTC-05:00)  #    Comments [10]