JG Vimalan's Blog

It is all about coding!

Unit test for Http Handler

In this post, I will discuss about creating unit tests for http handlers.

The functionality of my http handler is, it receives request from an ASP.NET page, processes it and sends back a response .

When I right clicked the ‘Process Request’ method in Http Handler and selected ‘Create unit tests…’, Visual Studio created unit test methods for me. But, when I tried to run those tests, I got the following error message, “The test adapter ‘WebHostAdapter’ threw an exception while running test…”.

So, the elegant way I can think of testing my custom http handler is, post data to the http handler url using HttpWebRequest and get the response back using HttpWebResponse.

Here is the unit test which I have written and it is working perfectly,

[TestMethod]
public void AuthTest()
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = postData += (“&username=” + “testuser@gmail.com“);
postData += (“&password=” + “testpassword”);

byte[] data = encoding.GetBytes(postData);

HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(“https://customerdemoserver/WebApplication2/Auth.ashx“);
myRequest.Method = “POST”;
myRequest.ContentType = “application/x-www-form-urlencoded”;
myRequest.ContentLength = data.Length;
myRequest.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

Stream newStream = myRequest.GetRequestStream();

newStream.Write(data, 0, data.Length);
newStream.Close();

HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
Stream stream = myResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();

Assert.IsNotNull(result);
}

Now, I am able to verify the functionality of my custom http handler, using the above unit test.

Advertisements

August 30, 2011 - Posted by | ASP.NET, C#.NET, VS 2010

4 Comments »

  1. excellent! thanks for sharing the code.

    Comment by Nizam | August 31, 2011 | Reply

  2. it gives an error Cannot send a content-body with this verb-type. in Stream newStream = myRequest.GetRequestStream(); part

    Comment by theresa | May 17, 2012 | Reply

  3. To fix this error, please set myRequest.Method = “POST”.

    Comment by JG Vimalan | May 17, 2012 | Reply

  4. I have written reverse proxy and added handler in asp.net 2.0 how can I unit test using Nunit.

    Comment by KD | January 5, 2013 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: