views:

444

answers:

4

I am looking for any kind of information (prefer Moq) on how to unit test the Application_Start method in Global.asax. I am using ASP.NET MVC and trying to get to that elusive 100% code coverage!

The fact that I'm using MVC is not the point. And saying that not testing Start is not necessary isn't really the answer either. What if I had other code in there? I need to know how to test it.

A: 

this function is called the first time your site is visited. recycling the app pool will cause it to be triggered again

In most situations, this event handler has no code, so don't waste time pursuing meaningless numbers!

Steven A. Lowe
I agree. There is no reason to test this event. If you are doing some logic that needs to be tested, extract it out and test it separately. Testing something that has this app pool dependency is very impractical.
Jab
+2  A: 

In a typical ASP.NET MVC application the Application_Start event is often used to register custom routes. Here's a nice post explaining how to unit test your custom routes.

Darin Dimitrov
A: 

If you want to test the actions of an event-based item like this, separate the actions into a separate, testable method and just call it from the handler. Or, as darin suggested, test the effects of the method - in this particular case, that your routing table got registered correctly.

BTW, I've never reached 100% coverage on a non-trivial app... We generally target 80% as "good enough". Some modules are 100% testable, but many aren't practical to do so.

GalacticCowboy
+1  A: 

I've found the best way to unit test stuff in Global.asax is to make sure the whole thing is in a testable static method.

Then pass in to that method everything it needs from Global.asax.

So for example, if you were doing a check of Session on Application Start, you could have a method like this:

public static void CheckSession(HttpSessionStateBase session)
{
...
}

Then, your Application Start would just be this:

protected void Application_Start(object sender, EventArgs e)
{
    CheckSession(new HttpSessionStateWrapper(Session));
}

This example is obviously a little silly as you'd probably do something like this in Session Start :) You could pass into that method whatever it needs, Request, Response, Cache, etc.

However, it gets the point across. The only code that wouldn't be covered would be the actual single line call in Application_Start. Everything else could be covered in a test using Moq like so: var session = new Moq(); ...Set Expectations... Global.CheckSession(session.Object); ...Do Asserts...

You wouldn't achieve the 100% code coverage you're looking for, but you'd be darned close, and you would be fulfilling the "spirit" of TDD law if not exactly the letter :)

CubanX