Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Unit Testing Override Initialize Method

I've got an abstract class shown below which gets inherited by all the other controllers. Is it possible to test this method at all? Btw, I'm trying to use MOQ but no luck. If you could help me will be much appreciated:

public abstract class ApplicationController : Controller
{  
    protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
       base.Initialize(requestContext);

       //do some stuff here
    }
}
like image 332
Nil Pun Avatar asked Apr 24 '11 06:04

Nil Pun


1 Answers

If you take a look at the source code of base Initialize method you will find out that what it does is that it sets up ControllerContext and url stuff. Now, download MvcContrib TestHelper and check out TestControllerBuilder . The builder sets up everything you need in order to have controller context and other stuff which you depend upon. Ok, we are not over yet - you wanted to test your own override of Initialize right? TestControllerBuilder doesnt call your Initialize because it does initialization in different way. I suggest you to factor out your custom Initialize() logic out into different method. Then create fake (stub) subclass with public method that calls this factored out protected Initialize. Are you with me?

something like:

public abstract class ApplicationController : Controller
{  

   protected override void Initialize(System.Web.Routing.RequestContext requestContext)
   {
      base.Initialize(requestContext);
      MyInitialzie()
   }
    protected void MyInitialize()
    {
       ControllerContext.XXX // do whatewer you want here. Context is already setted up
    }
}

class FakeController: ApplicationController 
{
   public void CallMyInitialize()
   {
      MyInitialize();
   }
}

Later in test class:

[Test]
public void MyInitializeTest()
{
    TestControllerBuilder builder = new TestControllerBuilder();
    FakeController controller = new FakeController();
    builder.InitializeController(controller);

    controller.CallMyInitialize();
    //TODO: verification of MyInitialize assumptions
}

Is that clear?

like image 140
Boris Bucha Avatar answered Oct 27 '22 00:10

Boris Bucha