Unit Testing and DTOs

I have been studying for the MCPD-Enterprise 3.5 exam this last week so I have been going though MSFT’s training materials.  I started with the 70-561 book and I noticed that each of the examples include a Unit Test.  I thought this was really cool – it is the 1st training kit I have seen that integrated Unit Tests.

 

MCTS Self-Paced Training Kit (Exam 70-561): Microsoft .NET Framework 3.5 - ADO.NET

Speaking of Unit Tests, I also have been playing around with Unit Testing in a side project that I have.  I built a dedicated DTO class (complete with Ent Lib validation), built my 1st factory method that serves up the DTO (CRUD and collections), and then created a Unit Test to test the Get Method.

I figured out quickly that reference types do not work like this:

            int AgeGroupId = 1;

AgeGroup expected = new AgeGroup(1, "Boys 6 And Under", "6 And Under", 1, "15 Yards", 1, "Male", 1);

            AgeGroup actual = AgeGroupFactory.GetAgeGroup(AgeGroupId);

Assert.AreEqual(expected, actual);

 

Because they are two different pointers pointing to two different locations on the heap.  I then thought about comparing each property like so:

 

            Assert.AreEqual(expected.AgeGroupId, actual.AgeGroupId);

            Assert.AreEqual(expected.AgeGroupDesc, actual.AgeGroupDesc);

            //ETC…

 

But that seemed like a huge pain to code each property.

Next, I thought about implementing the IEquatable<T> interface and build something like:

Assert.IsTrue(expected.Equals(actual));

But then I am still coding each property – though it is in a better place.  Finally, I thought about using the ToString() method that I already implemented in the DTO.  That worked the best for me – primarily because I had already coded it and I only added in the properties that are unique/important.

Assert.AreEqual(expected.ToString(), actual.ToString());

I might go back to the IEquatable<T> interface in the future – just to make the API more predictable.

I wonder how Mocking handles this – I will know more about that once I implement MOQ in my project (next month hopefully…)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: