Monday, June 27, 2011

Microsoft Moles!

This is a very cool project from Microsoft Research:

http://research.microsoft.com/en-us/projects/moles/

I'm able to use this to "fake" or "mock" sealed classes inside of the ASP.NET runtime.

For example:

        [TestMethod]
        [HostType("Moles")]
        public void WhenCannotInterpretSdnUserKeyAsIntegerThenMustRedirectToGlobalErrorPageWithProperMessage()
        {
            // Arrange
            var cookies = new HttpCookieCollection { new HttpCookie(SdnUserKeyCookieName, "Gibberish") };
            var context = new MHttpContext();
            var request = new MHttpRequest();
            var response = new MHttpResponse();
            var redirectWasCalled = false;
            var redirectedToLocation = string.Empty;
            var responseEnded = false;
            response.RedirectStringBoolean = (string location, bool endResponse) =>
            {
                redirectWasCalled = true;
                redirectedToLocation = location;
                responseEnded = endResponse;
            };
            MHttpContext.CurrentGet = () => context;
            context.RequestGet = () => request;
            context.ResponseGet = () => response;
            request.CookiesGet = () => cookies;

            // Act
            _sdnAuthenticator.Process(context);

            // Assert
            Assert.IsTrue(redirectWasCalled);
            Assert.AreEqual("/Error.aspx", redirectedToLocation, true);
            Assert.IsTrue(responseEnded);
        }

How cool is that? The moles are implemented as "detours" and replace components of the runtime when configured to do so.

This is great stuff.

0 comments: