
Monday, February 01, 2010
Testing Security Code with Moles
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: using System.Security.Principal; using System.Threading.Moles; using Microsoft.Moles.Framework; using Microsoft.VisualStudio.TestTools.UnitTesting;
[assembly: MoledType(typeof(System.Threading.Thread))]
namespace SecurityTest { [TestClass] public class UnitTest1 { [TestMethod] [HostType("Moles")] public void TestSecurityCode() { MThread.CurrentPrincipalGet = () => new GenericPrincipal(new GenericIdentity("dominick"), null);
var security = new SecurityCode(); var user = security.SomeMethod();
Assert.AreEqual("dominick", user); } }
public class SecurityCode { public string SomeMethod() { // simulates context Thread.CurrentPrincipal = new GenericPrincipal( new GenericIdentity("bob"), null);
return Thread.CurrentPrincipal.Identity.Name; } } }
Misc
Monday, February 01, 2010 10:36:20 AM UTC
|
|