Skip to main content

Improving “Boiler Plate” Data-Reader Code – Part 2

In Part 1 of this series we started with a basic Data-Reader / SQL Connection/Command pattern and illustrated how it is possible to abstract the parsing of the Data Reader into a standalone object that can be fully unit tested in isolation of the calling code.   In Part two of the series we will highlight a very simple optimisation that can be made to the “DataReader” convertor and the required update to the tests to capture/verify the changes.  In this revision the original “CustomerDRConvertor” has been updated to include extremely basic caching, which for the duration of the object’s existence should ensure that only the first call needs to reference the “GetOrdinal(…)” method to find the element index of each desired column.  Subsequent calls can then use this “cached” index to reference the column by position rather than name.

namespace DataAccess.Example
{
using System.Data;
using System.Data.BoilerPlater;

public class CustomerDRConvertorPart2 : IConvertDataReader<Customer>
{
private int idIndex = -1;
private int firstNameIndex = -1;
private int surnameIndex = -1;

public Customer Parse(IDataReader dataReader)
{
if (idIndex == -1)
{
idIndex = dataReader.GetOrdinal("Id");
firstNameIndex = dataReader.GetOrdinal("FirstName");
surnameIndex = dataReader.GetOrdinal("Surname");
}

return new Customer
{
Id = dataReader.GetGuid(idIndex),
FirstName = dataReader.GetString(firstNameIndex),
Surname = dataReader.GetString(surnameIndex)
};
}
}
}

In traditional ASP applications (back in the day) the above caching pattern used to result in reasonable performance gains.   I’ve not looked into the benefits within a modern day .NET application and in some instances could be classed as premature optimisation.  But for the purpose of this example it provides a perfect illustration as to how the abstracting the data reader parsing from the connection/command code can provide many benefits.  Updated objects can be developed and tested in complete isolation of the existing code and then plugged into the code base with only minimal changes.

This updated code can be verified using the unit test below.  In the test the “Parse(…)” method is called once and the mocked objects are verified that they were called correctly.  The “Parse(…)” method is then called again and the mocked objects verified to make sure that the second call only resulted in an additional call to the GetGuid(…) and GetString(…) methods.  Due to the very basic caching that was implemented there is no need for the second call to make any GetOrdinal(…) references, which the verification of the mocked objects can confirm.  The tests verify the expected behaviour, not the inner workings of any implementation of a DataReader object.

namespace DataAccess.Example.Tests
{
using System;
using System.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Moq;
using Assert = NUnit.Framework.Assert;

[TestClass]
public class CustomerDRConvertorPart2Tests
{
[TestMethod]
public void CustomerDRConvertor_GoodCall()
{

var dataReader = new Mock<IDataReader>();

dataReader.Setup(dr=>dr.GetOrdinal("Id")).Returns(1);
dataReader.Setup(dr=>dr.GetOrdinal("FirstName")).Returns(2);
dataReader.Setup(dr=>dr.GetOrdinal("Surname")).Returns(3);

var id = Guid.NewGuid();
const string firstName = "John";
const string surname = "Doe";

dataReader.Setup(dr=>dr.GetGuid(1)).Returns(id);
dataReader.Setup(dr=>dr.GetString(2)).Returns(firstName);
dataReader.Setup(dr=>dr.GetString(3)).Returns(surname);

var convertor = new CustomerDRConvertorPart2();

var customer = convertor.Parse(dataReader.Object);

Assert.That(customer.Id, Is.EqualTo(id));
Assert.That(customer.FirstName, Is.EqualTo(firstName));
Assert.That(customer.Surname, Is.EqualTo(surname));

dataReader.Verify(dr=>dr.GetOrdinal(It.IsAny<string>()), Times.Exactly(3));
dataReader.Verify(dr=>dr.GetOrdinal("Id"), Times.Once());
dataReader.Verify(dr=>dr.GetOrdinal("FirstName"), Times.Once());
dataReader.Verify(dr=>dr.GetOrdinal("Surname"), Times.Once());

dataReader.Verify(dr=>dr.GetGuid(It.IsAny<int>()), Times.Once());
dataReader.Verify(dr=>dr.GetGuid(1), Times.Once());

dataReader.Verify(dr=>dr.GetString(It.IsAny<int>()), Times.Exactly(3));
dataReader.Verify(dr=>dr.GetString(2), Times.Once());
dataReader.Verify(dr=>dr.GetString(3), Times.Once());

convertor.Parse(dataReader.Object);

dataReader.Verify(dr=>dr.GetOrdinal(It.IsAny<string>()), Times.Exactly(3));
dataReader.Verify(dr=>dr.GetOrdinal("Id"), Times.Once());
dataReader.Verify(dr=>dr.GetOrdinal("FirstName"), Times.Once());
dataReader.Verify(dr=>dr.GetOrdinal("Surname"), Times.Once());

dataReader.Verify(dr=>dr.GetGuid(It.IsAny<int>()), Times.Exactly(2));
dataReader.Verify(dr=>dr.GetGuid(1), Times.Exactly(2));

dataReader.Verify(dr=>dr.GetString(It.IsAny<int>()), Times.Exactly(4));
dataReader.Verify(dr=>dr.GetString(2), Times.Exactly(2));
dataReader.Verify(dr=>dr.GetString(3), Times.Exactly(2));
}
}
}

In part three of this series I will cover how the above code can be moved into an abstract base class for data access that all inheriting classes can utilise through interfaces and generics.

Part 3 builds on the code developed in parts 1 & 2 into a usable solution.

Comments

  1. I've finally got around to adding part 3, have updated this post with a link to it.

    ReplyDelete

Post a Comment

Popular posts from this blog

Mocking HttpCookieCollection in HttpRequestBase

When unit testing ASP.NET MVC2 projects the issue of injecting HttpContext is quickly encountered.  There seem to be many different ways / recommendations for mocking HttpContextBase to improve the testability of controllers and their actions.  My investigations into that will probably be a separate blog post in the near future but for now I want to cover something that had me stuck for longer than it probably should have.  That is how to mock non abstract/interfaced classes within HttpRequestBase and HttpResponseBase – namely the HttpCookieCollection class.   The code sample below illustrates how it can be used within a mocked instance of HttpRequestBase.  Cookies can be added / modified within the unit test code prior to being passed into the code being tested.   After it’s been called, using a combination of MOQ’s Verify and NUnit’s Assert it is possible to check how many times the collection is accessed (but you have to include the set up calls) and that the relevant cookies have …

Injecting HttpContextBase into an MVC Controller

It is a shame that when the ASP.NET MVC framework was released they did not think to build IoC support into the infrastructure. All the major components of the MVC engine appear to magically inherit instances of HttpContext and it’s related objects – which can cause no end of problems if you are trying to utilise Unit Testing and IoC. Reading around various articles on the subject just to get around this one problem requires the implementation of several different concepts and you are still left with a work around. The code below, along with the other links referenced in this article is my stab at resolving the issue. There’s probably nothing new here, but it does attempt to relate all the information needed to do this for Castle Windsor. The overview is that all controllers will need to inherit from a base controller, which takes an instance of HttpContext into it’s constructor. It then overrides the property HttpContext in the main controller class, supplying it’s own version…

Unit Testing Workflow Code Activities - Part 1

When I first started looking into Windows Workflow one of the first things that I liked about it was how it separated responsibilities. The workflow was responsible for handling the procedural logic with all it's conditional statements, etc. Whilst individual code activities could be written to handle the business logic processing; created in small easily re-usable components. To try and realise my original perception this series of blog posts will cover the unit testing of bespoke code activities; broken down into: Part One: Unit testing a code activity with a (generic) cast return type (this post)Part Two: Unit testing a code activity that assigns it's (multiple) output to "OutArguments" (Not yet written)So to make a start consider the following really basic code activity; it expects an InArgument<string> of "Input" and returns a string containing the processed output; in this case a reverse copy of the value held in "Input".namespace Ex…