Unit Testing 4.0 Web Forms Including Event Handlers Like Page_Load Using Dynamic

If you’re too lazy or just plain impatient, you can find the source code here.

So one of the biggest pains in a place that doesn’t lend itself well to be in pain has been trying to unit test web forms like how MVC controllers can be. Before 4.0, this was an aggrevation at the least. Something in between stubbing one’s toe and getting only chocolate icecrfeam when you ask for a @*&*ing swirl. Serious, how hard is it to pull the swirl lever? Really.

Anyways, so there are certain things in .net web forms that were pretty difficult to hande/mock/get around for testing. Let’s take session for instance. Session is a sealed class with a non public constructor. To make things more interesting, the Page class only has a get for the Session property. Now you could go through a lot of hell, mostly reflection, to get aroud this, but who wants to do that? Personally I gave web forms the ole one finger salute, but being that I am working with web forms again… yeah had to find a way to get around this. The answer? Stems from dynamic.

Basically what I had to do is create a class that has a Session property that is dynamic, and then replace the old Session call with a class that calls a property named Session. The effect to the code, as far as the immediate code behind is concerned, is just this simple adding of the class before the Session call. Far as the code to do this, it’s fairly easy too.

First I started with an interface since using an interface will help later if I need to mock.


This is the bread and butter. Basically we have a container that will hold the session object. Making the property dynamic allows it to be set to anything. All I have to worry about is that whatever I set it to has the functionality used by Session. This is started by implementing the interface fo use on the site:


And then one for use with testing:


How are these used? Well if we take a base page:


So what this does is holds two constructors; One for use by .Net when it runs the site and one for the test class when it is testing the page functionality. The second is a way to stop all the stuff that happens in the Page class constructor when it’s time to unit test this [explitive]. This might look familiar to people who have used things such as Dependency Injection with MVC to help with Controller testing. If not, the idea is simple. It basically just gives the Page the test handler we need it to use when testing. If we aren’t testing, then we let it just use the default handler.

You might wonder why I didn’t instantiate the live version in the constructor, and the answer is: Session isn’t ready to be used at constructor time when doing the normal web site thing. Therefore, it will be set the first time the SessionHandler property is called. If it’s a test, well then it’s fine to set it in the constructor since it is bypassing the normal web site… thing.

The unit test looks something like this:


As you can see, a test version of the handler is created and the Session object is replaced with a Dictionary since that’s what Session is… well it has more to it but the most used feature is the key/value match and it happens to be the only part of Session I show in this example.

Since there is the second, test only, constructor on the page, we don’t have to worry about any asp.net stuff getting in the way when instantiating the page. The page will look like this:


As it can be see, the replacement of the Session call with SessionHandler.Session allows the features of Session but also the testability it lacked for so long. It’s true that if you want to use other features of Session, if there are any and I can’t remember, you’ll have to just add them to the test version so they can be called at test time. I can’t do everything for you.

MVC3, Entity Framework, jQuery… Everything example

How would you like to have a project that has these features?

Dependency Injection
Entity Framework 4.0 with POCO
Inversion of Control with Castle
The IResult
jQuery
jQuery Ajax Posts
jQuery Custom Css
jQuery Validation
Mocking with Rhino Mocks
MVC 3/Razor
MVC Annotation Based Validation
What I call the Repository Pattern
Unit Tests - Integration With Entity Framework
Unit Test - MVC Controller Actions

And more s--t I can't think of right now!

What’s the price of this gem? Just your time which is worth nothing!

Where can you find it? Right here!

Requirements:

Visual Studios 4.0
Mvc 3
To open the solution and do a search and replace on "Tutorial" to set your directory paths.
A real f--king need to learn!

Act now, operators aren’t in existence since this is hosted on a website, but if they were they would be standing by!

Disclaimer:

This may or may not hit you with a wave of awesome. Be prepared for the worse case awesome scenario. I am in now way responsible for any heart stoppage due to the shock and awe power of the project.

Mock SQLAlchemy scoped_session query and Why Python is My BFF

sqlAlchemy has sessionmaker to create a session from which you can use query to get whatever you need. For example:

someSession.query(SomeTableRepresentationObject).filter...ect

If you’ve used sqlalchemy, nothing new going on here but it wouldn’t be me if I didn’t point out the obvious and take three sentences to do so.

Now what you may run into is something like this:

def getCountOfUsersByUserName(userName, session):
  return session.query(User).filter(User.userName == userName).count()

Ok now that I typed that out, I see it’s kind of a dumb method. But f–k it, what’s done is done.

Now from a testing situation, this could look tough. After all if you come from a more static language background like I did, you should know how hard things can be to mock at times. (.Net Session… I’m looking at you with judging eyes. Sooooo judging.) But this isn’t a static language, it’s Python.

For purposes of making things less confusing, which is hard for me, when I use the word “Object” I mean method OR class. And remember as always, “banana” is the safe word.

You see, to mock that out all you need is an object that has a query object that takes in something and a filter object on the query object that takes in something and has a count method on it. Yeah that totally makes sense. Try working it backward.

Filter has one parameter and a count method on it. Whatever that parameter is, it doesn’t matter since it is Python. As long as Filter takes in one parameter, you have a winner.

Query, like Filter, takes in one parameter and has a object named Filter on it. Once again, it doesn’t matter what’s passed into Query, just that it takes something in.

Session is basically an object that has no parameters and has a Query object on it.

Now in a static language, this would be annoying. You would need 3 interfaces and mock a whole ton of stuff dynamically with something like Rhino Mocks or just create a bunch of classes of those interfaces that you can pass in. Either way, there are complications. Once you get into things like Web Session or ViewState, it’s a ton of work. Python? Eh, you can do it in 20ish lines. How you ask? Well I’ll show you how!

	class mockFilter(object): #This is the ONE parameter constructor
		def __init__(self):
			self._count = 0
			self._first = dynamicObject()

		def first(self):  #This is the another method that's just coming along for the ride.
			return self._first

		def count(self):  #This is the needed Count method
			return self._count

	class mockQuery(object): #This is the ONE parameter constructor
		def __init__(self):
			self._filter = mockFilter()

		def filter(self, placeHolder): #This is used to mimic the query.filter() call
			return self._filter 

	class mockSession(object):
		def __init__(self):
			self._query = mockQuery()
			self.dirty = []

		def flush(self):
			pass

		def query(self, placeHolder):  #This is used to mimic the session.query call
			return self._query

  #and this... THIS IS SPARTA!!1111... yeah I know, I'm about 3 years too late on that joke.

How does this work? Say I have the method from above:

def getCountOfUsersByUserName(userName, session):
  return session.query(User).filter(User.userName == userName).count()

I could test it using this:

  session = mockSession()
  session.query('').filter('')._count = 0 #Initialize the mock session so it returns 0 from count()

  getCountOfUsersByUserName('sadas', session)

And boom, you have mocking in ten minutes or less or your code is free.

As you can see, the highly dynamic nature of Python makes it a great fit for any project that will need unit tests and mocking. And which project doesn’t? You know what I’m sayin’? You now what I’m saying’? High five!

Note: dynamicObject is …. nothing but a cheesy class that inherits Object but has nothing on it. (Turns out that if I did someObject = Object() I couldn’t do this since Object by default doesn’t contain the ability to add things dynamically… and this was by design.)

And yes, I just quoted myself. I am that awesome.

How to Use a Factory Method With Castle / WindsorContainer

In my last post, I showed you the wonder of the WindsorContainer and creating concrete objects from a config file… but I wasn’t done yet. In fact, if you looked at my example and used your keen sense of observation (I’m suspending my disbelief) you might have noticed a little somethin’ somethin’ in the config file that I didn’t explain:

  <component id="factoryB"
    type="CastleConfigTest.Factory.FactoryB, CastleConfigTest">
  </component>

  <component id="childClassB"
   type="CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"
   factoryId="factoryB"
   factoryCreate="Create">
  </component>

And:

  <facilities>
    <facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel" />
  </facilities>

What are these??? Could they be the proof of intelligent life we’ve been looking for? Sadly no, since they actually are part of something that sounds a lot more complicated then it is. Say you have this interface:

  public interface IBaseClassB
  {
    String ClassName();
  }

And this class:

  public class ChildClassB : IBaseClassB
  {
    public String ClassName()
    {
      return "ChildClassB";
    }
  }

Which is all pretty straight forward much like that woman’s answer to you asking her out, “God no.”

If you had read this post, you might guess where this is going. Or you might guess that I’m going to re-explain it because you are too lazy to go and read it. One of those is correct.

Once again like my last post I do something simple like this:

  var test = new ObjectFactory().Create<IBaseClassB>();

And what I get is a brand new shiny ChildClassB. I can hear the yawns from here SO I’ll change it up a bit. What if I need ChildClassB to come from a Factory? How the hell would I pull that off?

  public class FactoryB
  {
    public static IBaseClassB Create()
    {
      var test = new ChildClassB();
      //Do some stuff to test
      return test;
    }
  }

I no longer can just replace IBaseClassB with ChildClassB directly because I need FactoryB to do something for me first. (I cheated by just adding a comment where code might go.  Point is, something happens to ChildClassB before the factory returns it.) OH NO! WHAT AM I TO DO? HOW CAN I SOLVE THIS? DOES THE CAPSLOCK ADD SUSPENSE?

Guess what? That’s right, that’s where that config stuff at the top comes in. Here’s the config file in full:

<configuration>
  <components>
    <component id="factoryB"
      type="CastleConfigTest.Factory.FactoryB, CastleConfigTest">
    </component>
    <component id="childClassB"
     type="CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"
     factoryId="factoryB"
     factoryCreate="Create">
    </component>
  </components>
  <facilities>
    <facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel" />
  </facilities>
</configuration>

Ok so I lied, that’s not the full thing I have in my example that you can download, but it is what you need for this part. It’s actually pretty simple too. You just need to declare three things:

The factory class “FactoryB”

    <component id="factoryB"
      type="CastleConfigTest.Factory.FactoryB, CastleConfigTest">
    </component>

The interface you want to mask with the factory return (IBaseClassB)

    <component id="childClassB"
     type="CastleConfigTest.Interface.IBaseClassB, CastleConfigTest"  //This is the interface to look for
     factoryId="factoryB"  //This is the id from above where you declared the factoryB section
     factoryCreate="Create">  //This is the method to use
    </component>

and the Castle part for using factories

  <facilities>
    <facility id="factorysupport" type="Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Microkernel" />
  </facilities>

And that’s really it. From that, this should work:

    [TestMethod]
    public void Create_ClassB()
    {
      //This will call FactoryB.Create to create the ChildClassB for me
      var test = new ObjectFactory().Create();
      Assert.IsTrue(test.ClassName().Equals("ChildClassB"));
    }

Woo hoo! Now you can run home and impress your Wife/Husband/fiance/partner/thing that lives in your apartment and always seems to pay the rent late but doesn’t have any issue with eating everything in your fridge! Enjoy!

Castle, Rhino, Mocking, and Possibly You

So here’s the issue, you have a class that you new up within a class.

class SomeClass
{
  private HelperClass someHelperClass;

  public SomeClass()
  {
    someHelperClass = new HelperClass();
  }

  public String DoSomething()
  {
    return someHelperClass.DoSomeThing();
  }
}

You with me? Cause if you’re not, you’ve probably made a serious error in career choice.

Now what’s the problem with that situation? Testing. That SomeClass is tightly coupled with the HelperClass so that if you want to unit test DoSomething, you’re kind of screwed. Why? Say HelperClass has a database connection or does something that would update the database? Do you really want to create bad data every time you run this test? Do you really want the overhead of creating those connections and who knows what else? If you answered yes, again reconsider your career.

Now you could do something like this:

class SomeClass
{
  ....
  public SomeClass(HelperClass injectAHelperClass) <-- Change is right here genius.
  {
    someHelperClass = injectAHelperClass;
  }
  ...
}

Next step would be to mock the HelperClass in a unit test and pass in the mock object. But there’s a deeper problem. Deeper than G.I. Joe public service announcements. Yes that deep. What if you can’t pass in a mock through the constructor?? What if that helper class is being newed (Yes that’s a f–king word on this site) up in something like an attribute? What if your hair were to spontaneously catch on fire? Well you are back in the world of hurt my friend, except the hair thing might be an improvement. For the other two, there is something that can help and it’s name is Castle.

What is Castle? Well besides a word, it’s a collection of lots of stuff that helps with anything from mocking to tooth aches, but for this example we only need something that allows instantiation from a config file.

Now you might ask, “How can I be awesome like this site?” to which I answer, “You can’t.” Defeated you now turn your eyes back to the dilema and ask, “Config file? Instantiate? What will that do for me?”

Imagine this if you will… and I know this kind of thinking hurts you but just hang in there… Suppose you have a factory method that creates a instance for you. Something like this:

class SomeClass
{
  ....
  public SomeClass()
  {
    someHelperClass = new ObjectFactory().Create<IHelperClass>();
  }
  ...
}

BUT HOW DO IT CREATE THEM OBJECT FROM INTERFACE? Good question, though horribly asked.

Now it might seem odd since I am using a factory to create a helper but I haven’t shown you how the factory finds what to create. What if I told you there’s a way that it would simple look to a config file and know the type to create? What if I told you that in your test project the factory would create MockHelperClass but in the ui project it creates a HelperClass like before? You might think it’s magic. You might think Over the Top is the best movie of all time. You would be wrong on both accounts.

Now the answer is here if you don’t feel like reading the rest, and I can’t really blame you since I stopped reading after the first paragraph. However, if you actually want to see some of the magic in writing, mush on.

First thing you need are four dlls are Castle.Core, Castle.DynamicProxy, Castle.MicroKernel, Castle.Windsor, and Castle.ImSorryButThePrincessIsInAnother. (THERE ARE FIVE DLLS) Ok so one of those is a lie, but I’ll leave it up to you to figure it out. You could use my example to get them or go to here and try to figure out where they are. Course you could also spin around in a chair for five minutes because that would be about as brilliant as not just using my easy to find example. Either way, you need them.

Next the example needs an interface. Why an interface? Because it’s simple. Could I do this with a class? Far as I know as long as it’s not sealed and the concrete object inherits it. However for this example, ITS A MOOT POINT BECAUSE I’M USING AN INTERFACE.

namespace CastleConfigTest.Interface
{
  public interface IBaseClassA
  {
    String ClassName();
  }
}

Wow, beautiful. If you’re getting teary over that, you’re weird but I appreciate the passion. Now what else I need is a concrete class that implements said interface.

namespace CastleConfigTest.Class
{
  public class ChildClassA : IBaseClassA
  {
    public String ClassName()
    {
      return "ChildClassA";
    }
  }
}

Good golly Miss Molly, that’s fantastic. Now what does this all mean? It means that somehow using a config I will magically turn IBaseClassA into ChildClassA. Now for the hell of it, and for the ease of it, I have a test too.

    [TestMethod]
    public void Create_ClassA()
    {
      var test = new ObjectFactory().Create();
      Assert.IsTrue(test.ClassName().Equals("ChildClassA"));
    }

Ok so wait, what’s this ObjectFactory? It’s a class I’ve created that uses an object (WindsorContainer) that uses a config file to pull in specified types into a collection. Now I could get into that class, but I’d rather do the config file real fast. It’s name? Castle.config. AMAZING

<configuration>
  <components>
    <component id="childClassA"
     service="CastleConfigTest.Interface.IBaseClassA, CastleConfigTest"
     type="CastleConfigTest.Class.ChildClassA, CastleConfigTest">
    </component>
  </components>
</configuration>

So what does that all mean? Really nothing complicated. ‘service’ says, “Look for this” and ‘type’ says “Replace with this”. (No it doesn’t literally say that in the config file so stop looking) What’s the point of that? Simple, for every project you can have a separate Castle.config with the same ‘service’ value but a different ‘type’ value meaning that at run time you can replace the IBaseClassA with any class that implements IBaseClassA. Say in the test project you have a config:

...
     service="CastleConfigTest.Interface.IBaseClassA, CastleConfigTest"
     type="CastleConfigTest.Class.MockClassA, CastleConfigTest">
...

Now anytime IBaseClassA is called upon, MockClassA is almost instantly called in it’s place. Kind of like a stunt man in any action movie involving Bill Nighy.

Now one thing of special note, and by special I mean far from it, it helps if you set the config to Copy Always so that you know where the file is when the project is built. You don’t have to do that if you don’t want to, just like you don’t have to take showers. It’s just makes life easier for everyone.

Seems all great and good, but slight issue… What’s ObjectFactory? Well, here it is:

  public class ObjectFactory
  {
    //Tell it where the config file is.  Yes this is hardcoded but get over it.  You
    //  can change that if you like.
    private const String fileLocation = @"C:\Development\CastleConfigTest\CastleConfigTest\bin\Debug\";

    //This is the config file name.  I really hope you could tell that already.
    private const String fileName = "Castle.config";
    private WindsorContainer container;

    public ObjectFactory()
    {
      //Create a new container with the config file.
      container = new WindsorContainer(new XmlInterpreter(fileLocation + fileName));

      //Get all types in the container that implement IBaseClassA and make them
      // transient... ie only when needed.  If you don't believe me, go here and apologize later.
      // I'm sure you're used to that anyhow.
      var controllerTypes =
        Assembly
          .GetExecutingAssembly()
          .GetTypes()
          .Where(item => typeof(IBaseClassA).IsAssignableFrom(item));
      //And this I stole from someone but I can't remmeber who
      //  I don't really care though because chances are it was someone important
      //  and there's as much of a chance of someone important reading this as
      //  me sprouting a second me and doubling the worthless content on this site.
      //  After all, double of infinite is just the same damn thing.
      //  Not to mention this world isn't ready for that much pretty.
      controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                            where typeof(IBaseClassA).IsAssignableFrom(t)
                            select t;

      foreach (Type type in controllerTypes)
        container.AddComponentWithLifestyle(type.FullName, type, LifestyleType.Transient);
    }

    //And then this is the wondrous and obviously complex method used to do the creating.
    public T Create() where T : class
    {
      return (T)container.Resolve(typeof(T));
    }
  }

Wait what? That’s it? Well for the most part. Only thing that was difficult was the ObjectFactory, but that’s so easy even a… well you know the rest. And why wouldn’t you? That f–ing phrase has burned into your skull for the last 5 years and that’s a conservative guess. And yes, there is room for improvement so save your nerd rage typing. After all, you have plenty of room for improvement but you won’t see me fist typing a list of things with disgruntled comic fan boy like intensity.

Anyways, that’s the short of it and since I gave you an example somewhere crazy hidden in this mess I call a post, you should be able to pick it up from there. If you can’t, consult your physician because you most likely suffer from acute brain loss. Don’t worry though, you can still have a long career as a PowerPoint instructor.

And if you haven’t figured it out yet, this post is my April Fools joke.  Actual useful content on this site.  Don’t get used to it.