views:

69

answers:

1

My current project based in Asp .net makes considerable use of Http handlers to process various requests? So, is there any way by which I can test the functionality of each of the handlers using unit test cases? We are using Nunit and Moq framework to facilitate unit testing.

A: 

You sure can, although I haven't done myself "in anger".
Use a System.Net.WebClient to make HTTP calls against your handlers, and evaluate what comes back, that will allow you to test the public facing interface of the handler.

In this example I've hard-coded my target, and I'm using a method on the WebClient that will return a string.

The WebClient also gives you access to the ResponseHeaders, Encoding and other useful 'webby' stuff; you can also upload info as well.

using System.Net;

namespace UnitTestHttpHandler
{
    public class TestHarness
    {
        public static string GetString()
        {
            WebClient myWebClient = new WebClient();
            return myWebClient.DownloadString("http://localhost/Morphfolia.Web/ContentList.ashx");
        }
    }
}

You can then use the TestHarness to call the target HttpHandler and verify the results in your tests (or use a better approach to your testing if you know one - I'm not a unit testing guru).

    [TestMethod]
    public void TestMethod1()
    {
        string x = UnitTestHttpHandler.TestHarness.GetString();

        Assert.IsTrue(x.Length > 5);
    }
Adrian K
But we need to route (using config files) the request to the correct handler and the server also needs to be running, right? So how to simulate that?
MockedMan.Object
Yes, a web server will need to be running. As far as config goes, I can't speak from experience but would I assume it would be done in a similar way to specifying other setting via config when unit testing (?). Sorry I can't offer much more than that.
Adrian K