Wednesday 15 October 2008

How to use the HttpContext cache in a non-web (test) environment

Question:
How to test a class that relies on HttpContext.Current.Cache (or so) in order to work.
If you test this in NUnit, for example, there will be no current HttpContext around.
So abstract the access to the Context away and in the property you'll provide another cache if need is.

Attach Debugger macro in VS 2005/ 2008

Question:
How to use a macro in Visual Studio 2005/2008 to attach a debugger to a process?

Tuesday 14 October 2008

Call private methods of an object from a test assembly. (NUnit)

I have to test a class of Foo from my test assembly Foo.Test.
Unfortunately, many methods I should test are not public.

This class uses reflection to call private methods on any type or object for testing.

using System;
using System.Reflection;

namespace TestUtilities
{
public class TestHelper
{
public static object InvokeStaticMethod(System.Type type, string methodName, object[] parameters)
{
BindingFlags bindFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
return InvokeMethod(type, methodName, null, parameters, bindFlags);
}
public static object InvokeInstanceMethod(System.Type type, object instance, string methodName, object[] parameters)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
return InvokeMethod(type, methodName, instance, parameters, bindFlags);
}
private static object InvokeMethod(System.Type type, string methodName, object instance, object[] parameters, BindingFlags bindFlags)
{
MethodInfo methInfo;
methInfo = type.GetMethod(methodName, bindFlags);
if (methInfo == null)
{
throw new ArgumentException(String.Format("There is no method with name {0} on type {1}", methodName, type.Name));
}

object result = methInfo.Invoke(instance, parameters);
return result;
}

}
}