Welcome to MSDN Blogs Sign in | Join | Help

Bertan's Blog

Developer @ Developer Solutions
Unit testing legacy code and reflection

I was recently in a training about test driven development and in an exercise about testing legacy code, a very nice idea came up to inject mock objects to legacy code. The usual problem is that if a legacy code is not written taking testability in to account, there might a lot of hard coded dependencies to external sources such as databases which makes unit testing really difficult. In order to quickly unit test the legacy components, those dependencies should be replaced by mock objects so that unit tests won't require a deployed environment. There are several ways to do this, one way is to decide which object to use (mock or the actual component) based on the a global flag. This can be dangerous if the flag is not set to false when deploying to production environment. However by using reflection, you can avoid modifying the existing code and replacing the reference to the mock component in the unit test itself. Below is a quick code snippet in how you can achieve this:

CustomerReader reader;
Type objectType = typeof(reader);
System.Reflection.
FieldInfo field = objectType.GetField("DataLayer",
  System.Reflection.
BindingFlags.Instance |
  System.Reflection.
BindingFlags.NonPublic |
  System.Reflection.
BindingFlags.GetField);
field.SetValue(reader,
new Object());

This code snippet will change the value of reader.DataLayer which is a private field in the object. However there is one drawback to this method. The wrapper object that you are replacing must be inheritable otherwise you won't be able to create a mock object to replace the original instance. 

 

Posted: Wednesday, June 13, 2007 8:18 PM by bertaygu
Filed under:

Comments

No Comments

Anonymous comments are disabled
Page view tracker