I am by far no (unit) testing expert. But I always found it odd that I sometimes have to re-structure code to make it explicitly unit-testable.
One typical example is code that relies on some sort of context – e.g. Thread.CurrentPrincipal. I personally like this pattern in the .NET Framework – but it is not ideal for testing.
Recently I ran across Moles which is a mocking and stubs framework from Microsoft Research which has some features that can help here. Inspired by this video – I gave it a try.
The following code allows “faking” Thread.CurrentPrincipal:
public class UnitTest1
public void TestSecurityCode()
MThread.CurrentPrincipalGet = () =>
new GenericPrincipal(new GenericIdentity(“dominick”), null);
var security = new SecurityCode();
var user = security.SomeMethod();
public class SecurityCode
public string SomeMethod()
// simulates context
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity(“bob”), null);