Comparing RequestReduce with other popular minifiers by Matt Wrock

I have been asked several times now how RequestReduce compares or is different to such popular minification and bundling solutions like squishit, cassette and the upcoming Asp.Net 4.5 Minification and Bundling features. Before I say anything let me comment that RequestReduce is an OSS project and I make no money from this project and in fact lose quite a bit of time to it. This comparison is not at all intended to make a statement that the other solutions out there suck and therefore you should use my super cool Wrock star solution. The solutions currently out there are all great tools written by great developers. Also, I am a Microsoft employee and do not in any way wish to compete with my employer. I am nothing but supportive of the asp.net team’s progress in enhancing performance out of the box with ASP.NET 4.5. That all said, RequestReduce does take a unique approach to bundling and minification that I want to point out in this post.

Automatically Discovers CSS and Javascript with no code or config

One of my primary objectives with RequestReduce is to have it optimize a website with absolutely no coding intervention. My philosophy is that a developer or team should not have to adjust their style or conventions to work with an auto minifying tool. Currently most of the popular tools require you to either inject code or a control into your asp.net page or MVC view to act as the touch point that defines what should be minimized.

Being able to avoid adding suvh code is obviously ideal for legacy apps where you might not even have the ability to change code or have no idea where to begin. I also like it for green field projects. I just don’t think that a tool like RequestReduce should have a noticeable presence in your code.

RequestReduce uses a response filter to scan your response for all <link> tags in the head and all <script> tags in the page. As long as the href or src points to a url that returns a css or javascript content type, it will be processed by RequestReduce. The exception to this rule is javascript with no-store or no-chache in their response or that expire in less than a week. RequestReduce ignores those. Also, RequestReduce, by default, ignores javascript pulled from the google or Microsoft CDNs. The idea there is that such content has a high likelihood of already being cached on the user’s browser. RequestReduce does expose configuration settings and an API to give more fine tuned control of what CSS and Javascript to filter.

Minifies and Combines External and Dynamic Content

Most of the popular minification and bundling solutions are file based. In other words, they pull down the original unminified resources via the file system and assume everything is already on your server. While this obviously covers most cases it does not cover external scripts or things like WebResource.axd and ScriptResource.axd which are generated dynamically.

RequestReduce is HTTP based. It pulls down original content via http which means it can pull down any css or javascript as long as it is publicly available from a url. This is great for a lot of blog and cms systems that heavily rely on Webresources and scriptresources. It is also great for external content. Now, as started above, RequestReduce ignores “near future” expiring scripts. However, toward the top end of my backlog is a feature to handle those. Imagine being able to include those pesky social media scripts.

Automatically Sprites CSS Background images

Anyone who has created sprite sheets from scratch knows how tedious that process can be. As a site adds images on new releases, those sprite sheets have to be revised which has an engineering cost and a risk of being forgotten. Ask your engineering team who wants to do the spriting and don’t expect a huge show of hands. RequestReduce parses the CSS and looks for images that it thinks it can sprite and then generates the sprite sheets on the fly.

There are limitations in what RequestReduce will find and potential to distort the page rendering in some cases when images are already sprited. Much of that can be easily mitigated. Please see this wiki and also this one for hints and explanations on how to improve and optimize the RequestReduce spriting experience. The very next feature I am working on should alleviate a lot of the mess that can sometimes occur with a fraction of sites that already have sprites and will also allow RequestReduce to sprite even more images. I have a few upgrades planned to address sprites. I also plan to address spriting foreground images. How cool would that be?

Deferred Processing

RequestReduce never blocks a request while waiting to minify and bundle resources. If RequestReduce has not already done the minification and bundling, it will send the original response and queue the resources for processing. In the case of RequestReduce this is particularly important since the spriting can be quite costly. Once resources have been processed, all subsequent requests for those resources will serve the optimized content using optimized caching headers and etags.

SqlServer Content Synchronization and easy integration with CDNs and Cookie-Less domains

RequestReduce allows you to easily configure an alternate hostname where you would like requests for static resources to be sent. This works great for CDNs and cookie less domains and it supports web performance best practices.

Also, since RequestReduce can synchronize optimized content via sql server, it becomes an ideal solution for many web farm implementations. A common problem in a web farm scenario is a request for the base page provides Urls for scripts and CSS that point to the optimized files. Then a different server receives these requests and if those resources have not been processed yet on that server, a 404 can ensue. This can also be handled with a common static file share. See this wiki for more into on this.

Now a lot of the current solutions out there do provide integration points for you to extend their processing and plug in these kinds of features into their frameworks. RequestReduce attempts to provide these features out of the box.

Why not just do all of this at Build Time?

This is another common and somewhat related question I get. On the one hand, I totally agree. In fact in probably most scenarios out their on the net today, a build time solution will suffice. Most sites don’t deal with dynamic or external content which are the areas where a build time solution simply won’t work. A build time solution also imposes a lot less risk. There are no extra moving parts running in production to minify and bundle your code that can break. If this breakage interferes with your sites ability to serve its css and Javascript ,the results can be akin to total down time. Also, with a build time solution, you know exactly what is going into production and your test team can confidently sign off on what they tested.

I intend to eventually add features to RequestReduce to provide a better build time experience. To me, the beauty of a run time solution is not having to worry about declaratively adding new resources to the build tasks. As long as the tool is stable, I can have confidence that the new resources (images, css and javascript) will get picked up in the optimization. Also, the potential for optimizing external resources can potentially be huge. There is a fair amount to be done here to fully leverage this potential but it is a fact that much of a web’s performance degradation can be blamed on resources served from external sites.

I really hope this answers many of the questions about what makes RequestReduce different from other similar tool. Please do not hesitate to ask for more clarification in the comments if it does not or if you feel like I have missed anything significant

Setting Response.Filter after Response.Redirect can cause a Filtering is not allowed HttpException by Matt Wrock

I ran into this error on a RequestReduce bug and there was not a whole lot of information pointing to a cause and remedy. So I’m posting this in the hopes that it will help the Google Lords find a solution more quickly for others.

So if you are using Razor templates in Asp.Net and you issue a Response.Redirect at some point either in the template itself or from a method that the template calls like Html.RenderAction for example, and then you later set a response  filter by calling Response.Filter, you will receive an HttpException stating “Filtering is not allowed.” It may look a little like this friendly message:

System.Web.HttpException (0x80004005): Filtering is not allowed.at System.Web.HttpResponse.set_Filter(Stream value)at RequestReduce.Module.RequestReduceModule.InstallFilter(HttpContextBase context) in c:\RequestReduce\RequestReduce\Module\RequestReduceModule.cs:line 223at System.Web.HttpApplication.SendResponseExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

For example, consider this Razor page:

@{    Layout = null;}

<!DOCTYPE html>

<html><head runat="server">    <title>index</title></head><body>    <div>@{ Html.RenderAction("Redirect"); }    </div></body></html>

Now assume we have a very simple action method like this:

public ActionResult Redirect(){    Response.Redirect("/Home/target");    return View();}

Ok. That’s kind of silly code but this is just to illustrate an example. And besides, who doesn’t like to be silly sometimes. Now it so happens that You have an HttpModule that sets a Response Filter. Here is what you should do:

if(!Response.IsRequestBeingRedirected)    Response.Filter = myFilter;

If you neglect to use the If statement checking for a redirect, you will be sorry. Unless of course you enjoy a white background with black text inside yellow boxes.

While my encounter to this has been with Razor templates and this does not reproduce using Web Forms views, I would still check for redirects before setting a Response Filter in any context. There is no reason that I can think of to ever filter a response that is being redirected.

Microsoft blogging platform gains 33% performance boost after adopting RequestReduce by Matt Wrock

Here is a Keynote performance graph covering a few hours before and after launch.

pic.twitter.com/UoqwYVWz

Looks good to me.

A win for Microsoft. Another win for the Open Source Community

Today Microsoft completed its onboarding of RequestReduce on its MSDN and Technet blogging platform. Huge thanks and shout out to Matt Hawley(@matthawley) who played a pivotal roIe in this launch! In fact, he DID launch it. Matt also made a significant contribution to RequestReduce by yanking out the .net 4.0 dependent SqlServer Store into a separate package and tweaking the build script to make it compatible with .net 3.5.

I am very pleased to report that upon launch, readers can now access a site that is 33% faster than it was before launch. This is a win for Microsoft, the multitudes of readers that visit its content every day and a win for the open source software (OSS) community at large. I like to think that this demonstrates Microsoft’s growing commitment to OSS. In just the past couple of years, Microsoft has made giant strides to fostering the open source ecosystem. This is just another small step forward.

Just to be clear: I am a Microsoft employee. However, I develop RequestReduce on my own time away from work and there have been non-Microsoft contributions. The features that I build into RequestReduce do not originate from some grand Microsoft Project gnat chart. My releases of RequestReduce downloads do not require multiple levels of sign off from the Microsoft covenant of elders.

Furthermore, my team and the teams I work closely with use tons or various OSS projects with the full blessing of the Microsoft Legal department (I hear they wear special underwear but am not sure – more on this later). We use nHibernate, StructureMap, Moq, XUnit, Caste Windsor, Service Stack, Json.Net, PSake and a lot more. These are baked into Microsoft properties that many .net devs visit every day like the Visual Studio Gallery, various MSDN properties and even the web service you call when you go to Visual Studio’s Extension Manager.

RequestReduce: Optimized for improving performance of brown field apps

While RequestReduce is suited to optimize any website, it is particularly ideal for sites that have already been built and suffering from poor, and sometimes extremely poor, performance. The MSDN and Technet blogging platform is a perfect example of this. They are built on top of 3rd party non-Microsoft blogging software that uses asp.net 3.5. Lets just say there were no lack of webresource.axd and scriptresource.axd especially if you are fond of fitting…say…30 or 40 in a single page. I mean why not? Certainly god created the .axd extension for a reason and intended it to multiply and be fruitful.

RequestReduce is ideally architected for these  scenarios. It follows a simple drop in and just work model. Unlike a lot of the other minify and bundling solutions it filters your page and dynamically locates your JavaScript and CSS regardless if its on your server or twitter’s CDN. It can process any resource with a text/css or JavaScript  mime type even if they are dynamically generated like in the case of ScriptResources. It works well with high traffic, multi server enterprise topologies because it is fast and provides multiple caching solutions including one that caches in a central SqlServer instance.

So what exactly does RequestReduce do?

Well after helping you lose weight, quit smoking and significantly enhancing your sex life (I did say “significantly” right?…good), it makes your website faster by minimizing your css and JavaScript. Combining your css and what JavaScript it can without breaking your scripts and it attempts to locate background images it can combine into sprite files. It also optimizes the color palette and compression of these sprites. Its like running YSLOW and then clicking the “optimize now” button. Really? You haven’t seen that button?

The end result is a less bytes and fewer HTTP requests your browser has to handle to render a page with very little work. Do you really want to generate your own sprites each time you are handed a new image or remember you have forgotten to add that new script to your bundling config?  Do you get frustrated when your site goes to production and you realize you forgot to spell Cace-Cntrl and your test team did not catch this because they were busy ensuring your app solved world hunger even if a user entered a space followed by an asterisk in your search box? Well you can get this functionality on your own site now at http://www.requestreduce.com or via Nuget.

Released RequestReduce.SassLessCoffee: Now have RequestReduce compile your .less, .sass, .scss and .coffee files before minifying and bundling them by Matt Wrock

I’ve been wanting to get this post out for a few days since I launched this last Friday. I have to make this quick before I hop in the shower to go to work. I owe at least that to my coworkers.

Less, Sass and Coffee script compiling

I’ve had a few RequestReduce users asking me about adding Less, Sass and Coffee script compiling to RequestReduce. Technically, this has been doable for some time along side DotLess and SassLessCoffee.AspNet. However, I wanted to optimize the integration since by default, using the handlers provided by those two excellent projects bring in their own caching and, in the case of SassAndCoffee, its own bundling and an issue with setting “near” future caching headers (which is now fixed in the latest source code). This extra caching and bundling just adds unnecessary processing time and possibly disk space consumption.

RequestReduce.SassLessCoffee, available at http://RequestReduce.com and via Nuget now calls into the APIs exposed by both DotLess and SassAndCoffee.Core to have them simply compile the contents of your .less, .sass, .scss and .coffee files. RequestReduce then takes over with its own minification, bundling and caching logic.

To get this simply requires adding the RequestReduce.SassLessCoffee Dll and those of its dependencies to your project. No handler config entries are necessary in your web.config. This is because RequestReduce will map these extensions to its own handlers at run time.

Hopefully this is what the Less/Sass/Coffee users have been looking for in RequestReduce. Please let me know if you run into issues here.

New Look on the RequestReduce Homepage

I gave RequestReduce.com a facelift last weekend. A couple weeks ago Zach Holman gave me some good advice on my github readme. He commented that my headline and the first paragraph was too wordy. I had felt the same way for a while but this weekend finally did something about it. I shortened up my github headline and readme and took it a step further and totally revamped the homepage. It looked more like an essay than a pitch for RequestReduce. When I’m looking for OSS solutions, I typically don’t like essays as my introduction to the project. So now the first thing you see are basically bullet points highlighting what's important and some before and after images from www.webpagetest.org waterfall tests.

I’d really be interested in hearing your feedback on the new look. I already shrunk the huge Getting Started font based on some early comments. Does this quickly “bring the message home?” I did get a comment about the waterfall images appearing out of context and that the reader may not know what they are or why they are important. Their importance seem clear to me but then I do perf testing every day unlike a lot of other devs and web folk.

Unit Testing ASP.Net Http Handlers and a discussion of Auto Mocking and the Testable pattern by Matt Wrock

This post was originally entitled Unit Testing ASP.Net Http Handlers and my intent was a quickie (5 minute) post on overriding ProcessRequest in a test friendly manner. Then, struck by diarrhea of the fingers, I found myself going off on unit testing practices and discussing a pattern I don’t hear a lot about but that provides a lot of value to me and the teams I work with. I hope you will find it of value too.

A test friendly IHttpHandler

The default Http Handler template that Visual Studio provides is not very Unit Test friendly. The key problem is here:

public void ProcessRequest(HttpContext context){

}

 

HttpContext is not your friend and it will eat your children if left unattended. Thankfully there is HttpContextBase who loves you and has a wonderful plan for your life. If you are not familiar with HttpContextBase, it provides everything that HttpContext has to offer wrapped up in mockable abstract classes.

Its really quite simple to transform the default visual studio HttpHandler template to a unit test friendly template. Use this instead:

using System.Web;

namespace RequestReduce.SassLessCoffee{    public class IISHandler1 : IHttpHandler    {        public bool IsReusable        {            get { return true; }        }

        public void ProcessRequest(HttpContext context)        {            ProcessRequest(new HttpContextWrapper(context));        }

        public void ProcessRequest(HttpContextBase context)        {            //write your handler implementation here.        }

    }}

Now your unit tests can call ProcessRequest and pass in a mocked context which in turn will call the IHttpHandler contractual ProcessRequest.

As an example of a full fledged real world set of unit tests, I’ll use a handler that I am creating and will very soon release in my RequestReduce project which compiles .less dynamic css to plain old css.

Here is the Handler:

using System.Web;using RequestReduce.Utilities;using dotless.Core;using dotless.Core.configuration;

namespace RequestReduce.SassLessCoffee{    public class LessHandler : IHttpHandler    {        private readonly IFileWrapper fileWrapper;

        public LessHandler(IFileWrapper fileWrapper)        {            this.fileWrapper = fileWrapper;        }

        public void ProcessRequest(HttpContext context)        {            ProcessRequest(new HttpContextWrapper(context));        }

        public void ProcessRequest(HttpContextBase context)        {            var localPath = context.Request.Url.LocalPath;            var response = context.Response;

            try            {                var source = fileWrapper.GetFileString(localPath);

                response.ContentType = "text/css";                response.Write(new EngineFactory(new DotlessConfiguration                                                     {                                                         CacheEnabled = false                                                     }                                   ).GetEngine().TransformToCss(source, localPath));            }            catch (System.IO.FileNotFoundException ex)            {                response.StatusCode = 404;                response.Write("/* File Not Found while parsing: " + ex.Message + " */");            }            catch (System.IO.IOException ex)            {                response.StatusCode = 500;                response.Write("/* Error in less parsing: " + ex.Message + " */");            }        }

        public bool IsReusable        {            get { return true; }        }    }}

As you can see there is not much going on here in my code thanks to the DotLess compiler. I simply want to expose my own handler instead of the DotLess handler which does pretty much the exact same thing but I turn off the caching since RequestReduce has its own. This handler will ship as part of my own Nuget package providing Sass and Coffee compiling as well that will automatically wire up the handler mapping configuration from within the core RequestReduse assembly.

There are really four things I want to test here:

  1. Make sure I am setting Content type to text/css.
  2. Make sure that I am successfully calling out to the compiler with .less and getting back css.
  3. Ensure I return a 404 if there is no .less file associated with the .less URL being called.
  4. Return a 500 if something wrong happens in the compile.

Here is my Test Class:

using System;using System.IO;using System.Web;using Moq;using RequestReduce.SassLessCoffee;using RequestReduce.Utilities;using Xunit;

namespace RequestReduce.Facts.SassLessCoffee{    public class LessHandlerFacts    {        class TestableLessHandler : Testable<LessHandler>        {            public TestableLessHandler()            {

            }        }

        [Fact]        public void WillSetCorrectContentType()        {            var testable = new TestableLessHandler();            var context = new Mock<HttpContextBase>();            context.Setup(x => x.Request.Url)                .Returns(new Uri("http://localhost/RRContent/css.less"));            var response = new Mock<HttpResponseBase>();            response.SetupProperty(x => x.ContentType);            context.Setup(x => x.Response).Returns(response.Object);

            testable.ClassUnderTest.ProcessRequest(context.Object);

            Assert.Equal("text/css", response.Object.ContentType);        }

        [Fact]        public void WillWriteCompiledLess()        {            var testable = new TestableLessHandler();            var context = new Mock<HttpContextBase>();            context.Setup(x => x.Request.Url)                .Returns(new Uri("http://localhost/RRContent/css.less"));            var response = new Mock<HttpResponseBase>();            context.Setup(x => x.Response).Returns(response.Object);            testable.Mock<IFileWrapper>().Setup(x => x.GetFileString(It.IsAny<string>()))                .Returns("@brand_color: #4D926F;#header {color: @brand_color;}");            var result = string.Empty;            response.Setup(x => x.Write(It.IsAny<string>())).Callback<string>(s => result = s);            const string expected = "#header {\n  color: #4d926f;\n}\n";

            testable.ClassUnderTest.ProcessRequest(context.Object);

            Assert.Equal(expected, result);        }

        [Fact]        public void WillReturn404IfFileNotFound()        {            var testable = new TestableLessHandler();            var context = new Mock<HttpContextBase>();            context.Setup(x => x.Request.Url)                .Returns(new Uri("http://localhost/RRContent/css.less"));            var response = new Mock<HttpResponseBase>();            context.Setup(x => x.Response).Returns(response.Object);            testable.Mock<IFileWrapper>().Setup(x => x.GetFileString(It.IsAny<string>()))                .Throws(new FileNotFoundException());            response.SetupProperty(x => x.StatusCode);

            testable.ClassUnderTest.ProcessRequest(context.Object);

            Assert.Equal(404, response.Object.StatusCode);        }

        [Fact]        public void WillReturn500IfIOExceptionIsThrown()        {            var testable = new TestableLessHandler();            var context = new Mock<HttpContextBase>();            context.Setup(x => x.Request.Url)                .Returns(new Uri("http://localhost/RRContent/css.less"));            var response = new Mock<HttpResponseBase>();            context.Setup(x => x.Response).Returns(response.Object);            testable.Mock<IFileWrapper>().Setup(x => x.GetFileString(It.IsAny<string>()))                .Throws(new IOException());            response.SetupProperty(x => x.StatusCode);

            testable.ClassUnderTest.ProcessRequest(context.Object);

            Assert.Equal(500, response.Object.StatusCode);        }    }}

Here are a few things I’ll call out here that may be of interest:

The three A’s: Arrange, Act and Assert

This is a common paradigm in unit testing and provides an initial and very basic way of framing your tests. Start with Arranging your tests, then Act by calling the method you are testing and lastly Assert that what you expect to be true (or false) really is as it should be. Now, for some reason the code snippet editor I use in Live Writer, my blog editor of choice, has decided that I really did not need the extra line breaks that I typically insert between my arrange, act, and assert code. So for clarity:

//ARRANGEvar testable = new TestableLessHandler();var context = new Mock<HttpContextBase>();context.Setup(x => x.Request.Url)    .Returns(new Uri("http://localhost/RRContent/css.less"));var response = new Mock<HttpResponseBase>();response.SetupProperty(x => x.ContentType);context.Setup(x => x.Response).Returns(response.Object);

//ACTtestable.ClassUnderTest.ProcessRequest(context.Object);

//ASSERTAssert.Equal("text/css", response.Object.ContentType);

XUnit and Moq are my TDD tools of choice

You will certainly note the using statements referencing these libraries at the top. Over the years I have used different tools for testing and mocking and these are the ones that have stuck because they are simple and just feel natural to me. I encourage you to try them as well.

Dependency Injection, the Testable pattern, and Auto Mocking

Dependency Injection

Both at work and here at play, I make heavy use of Dependency Injection. In short, this is a pattern whereby you inject services into a class often, but not always, via a constructor and usually in the form of interfaces or abstract classes that are wired up through an IOC container like StructureMap (what I use) or one of many other containers with similar quality and functionality. If you are not familiar with Dependency Injection (DI) or IOC (Inversion of Control) containers, please stop reading this and go to your favorite search engine (mine is google and, who are we kidding, so is yours) to find out more.

I use dependency injection for several reasons and one of those reasons is testability. By injecting the interfaces of services that I need I accomplish two (probably several more) things:

  1. The logic included in those services can be tested elsewhere in their own test classes and isolating them in this way allows me to focus just on the logic executed by the class I am currently testing.
  2. By using interfaces, I can easily mock the expected behavior of those services. This way I don’t have to call those services directly which would require me to possibly set up all sorts of other stuff like files and database connections (yuck).

This handler demonstrates an extremely simple use of DI:

private readonly IFileWrapper fileWrapper;

public LessHandler(IFileWrapper fileWrapper){    this.fileWrapper = fileWrapper;}

My concrete implementation of IFileWrapper has all sorts of methods that do all sorts of fun and wonderful things with files. But who wants to deal with actual files in a unit test? I don’t.

The Testable Pattern

The Testable pattern, which I believe was coined by Brad Wilson (@bradwilson) co creator of XUnit, provides a nice structure for testing classes that use DI. Brad writes about it here. Essentially it involves creating a sort of wrapper class that derives from the actual class you are testing and exposes mocked, stubbed or faked implementations of its injectable services. The unit test class then works directly with this “Testable” class. A nice naming convention here is to call this testable class Testable[Your class under test name here]. Hence the class name I use: TestableLessHandler.

Auto Mocking

You may wonder why my testable class is so sparse. Well, they did not used to be. They used to look something like this:

class TestableLessHandler : LessHandler{    public Mock<IFileWrapper> MoqFileWrapper { get; set; }

    public TestableLessHandler(Mock<IFileWrapper> moqFileWrapper)        : base(moqFileWrapper.Object)    {        MoqFileWrapper = moqFileWrapper;    }

    public static TestableLessHandler Create()    {        return new TestableLessHandler(new Mock<IFileWrapper>());    }}

Well after writing about a hundred of these and often with many more than one dependency, I began thinking there has got to be a better way. And there is! Its called Auto Mocking, Something I have truly grown to love in an HR friendly sort of a way. My new testables look like this:

class TestableLessHandler : Testable<LessHandler>{    public TestableLessHandler()    {        //place for default mock setups    }}

I use StructureMap’s StructureMap.AutoMocking utility to accomplish this. You don’t have to use the full blown StructureMap IOC to use this. It is available as a separate Nuget package you can pull into your VS project and has a MoqAutoMocker class that works nicely with Moq. What auto mocking does is it looks at the dependencies that your class under test use and automatically creates Mocked implementations of the dependencies. Isn’t that nice?

I wrap up the auto mocking wire up in a class called Testable:

using System;using StructureMap.AutoMocking;using Moq;

namespace RequestReduce.Facts{    public class Testable<TClassUnderTest> where TClassUnderTest : class    {        protected MoqAutoMocker<TClassUnderTest> autoMocker =             new MoqAutoMocker<TClassUnderTest>();

        public Testable()        {

        }

        public Testable(Action<Testable<TClassUnderTest>> setup)        {            setup(this);        }

        public Mock<TDependencyToMock> Mock<TDependencyToMock>()             where TDependencyToMock : class        {            var a = autoMocker.Get<TDependencyToMock>();            return Moq.Mock.Get(a);        }

        public void Inject<T>(T type)        {            autoMocker.Inject(type);        }

        public void InjectArray<T>(T[] types)        {            autoMocker.InjectArray(types);        }

        public TClassUnderTest ClassUnderTest        {            get { return autoMocker.ClassUnderTest; }        }    }}

This is the first class that I add to any test assembly I create. I cannot take credit for writing this class. I’m not sure exactly who wrote it but it came from a team lead by my colleague Tim Shakarian (aka tshak). This class uses a combination of StructureMap.AutoMock and Moq to allow me to create a testable instance of my class that automatically exposes all of its dependencies via Moq Mocks.

So my test method uses TestableLessHandler like so:

//Create the testablevar testable = new TestableLessHandler();...//Access my depencency via Mock methodtestable.Mock<IFileWrapper>().Setup(x => x.GetFileString(It.IsAny<string>()))    .Returns("@brand_color: #4D926F;#header {color: @brand_color;}");...

//call method I want to test via the ClassUnderTest propertytestable.ClassUnderTest.ProcessRequest(context.Object);

After creating the testable, I can access its mocked dependencies via the Mock method. Not shown here, but something I often use, is the Inject method. I can say:

testable.Inject<IFileWrapper>(new SomeOtherFakeorRealFileWrapperImplementation())

When all the mock setups, callbacks, etc. are just as I want them to be and I’m ready to actually test my class, I can access the true class via the ClassUnderTest property.

Perhaps I’ll wrap up this testable into a Nuget package to make it easy for others (and me) to pull it into their test projects.

So hopefully this is useful to others. Ooops. spent too much time writing this and now I won’t be finishing my RequestReduce.SassLessCoffee Nuget package before work. Oh well…maybe tomorrow or tonight.