views:

34

answers:

1

I am using MvcContrib and the TestControllerBuilder to write tests for my controller.

I am writing the tests for my Error Handling Controller that looks like this:

    public JsonResult HttpError()
    {
        Exception ex = null;

        try
        {
            ex = (Exception)HttpContext.Application[Request.UserHostAddress.ToString()];
        }
        catch
        {
        }

        if( ex != null )
        {
            return Json( new ErrorViewModel() { Message = ex.Message, Source = ex.Source, StackTrace = ex.StackTrace, Type = ex.GetType().Name}, JsonRequestBehavior.AllowGet );
        }
        else
        {
            return Json( new ErrorViewModel() { Message = "An error has occured." }, JsonRequestBehavior.AllowGet );
        }
    }

Basically, my global error handling puts the last exception into the Application store and this controller tries to pull it back out, convert it to Json, and return it (we are returning everything as Json because these methods are only getting called as Web Services).

To fully test this, I need for UserHostAddress to contain something predictable, but the objects setup by TestControllerBuilder leave that property null.

How can I make this work? I'm not sure how I can make this work in my test.

A: 

TestControllerBuilder uses Rhino.Mocks for mocking the HttpContext. Knowing this, you could put the Request object back into "record" mode and stub out a response:

controller.Request.BackToRecord();
controller.Request.Stub(r => r.UserHostAddress).Return("75.142.12.45");
controller.Request.Replay();

Do this after you've initialized the controller, but before your method call.

Patrick Steele