Ryan Kyle's Tech Blog

Out of the mouth of a developer

Use of Delegates in Unit Tests to Simplify Code in C# .NET

I’ve been writing a program in .NET that analyzes number sequences. I’ve been doing my best to follow TDD practices. In doing so, I’ve spend hours writing tests and little actual code yet.

In the process I ran into an issue of duplicate code in my tests. I found myself copy/pasting test code just to change the method that was called during that particular test. Hmm… that’s not good practice.All the methods had one of two method signatures. I thought to myself: “I’m sure there’s a better way of doing this”. And sure enough, after writing a quick example program of delegates, I discovered my solution. This post takes the form of a refactor rather than writing tests from scratch.

None of these steps should take long to perform since very little new code is being written. This process took me 15 minutes total. I will write example code for all this soon and post it.

 

Steps: Test, Identify, Declare, Rewrite one, Test, Rewrite, Test.

Step 1: Run all the existing tests you plan to modify and note their result.

Step 2: Identity the method signatures that are commonly being used.

Step 3: Declare delegates using the method signatures from step 1. I made them private fields in the test class.

Step 4: Factor out the test code into a separate method that takes arguments including the delegate.

Step 5: Rewrite the first test using the delegate, above the existing code. Comment out the old code instead of deleting it!

Step 6: Run the test! It’s very important to run that test to make sure that your new test code came to the same conclusion as your old test code. It doesn’t hurt to step through the test code briefly to make sure everything flows smoothly.

Step 7: Rewrite the rest of the tests that are very similar.

Step 8: Run all your rewritten tests. See step 5 for more detail.

 

Use of delegates in unit tests - all

 

Alright! You’ve greatly simplified your unit tests by using delegates. This is likely a niche technique, but quite useful if you have a need. If you have more innovative uses for delegates, write a blog post and then post a link to it in the comments.

 

Ryan D. Kyle | Concord Mfg LLC

July 24, 2010 Posted by | Learning | , , , , , , , | 2 Comments

   

Follow

Get every new post delivered to your Inbox.