Unit testing JSON services part 2.

Continuing with unit testing the ASP.Net MVC JSON service I am playing arround with, I got arround to the login action. For whatever reason, an instance of WebClient does not preserve cookies across multiple requests. What that meant was that all thought I was logging in fine, subsequent calls were failing due to authentication.

Fortunately it’s quite easy to make WebClient preserve the cookies. Heres how:http://couldbedone.blogspot.com/2007/08/webclient-handling-cookies.html

I rolled that into a class called JsonWebClient, along with the other options I was setting on the standard WebClient in each test.

public class JsonWebClient : WebClient
    public JsonWebClient()
        this.Encoding = UTF8Encoding.UTF8;
        this.Headers.Add(HttpRequestHeader.ContentType, "application/json");

    private CookieContainer container = new CookieContainer(); 
    protected override WebRequest GetWebRequest(Uri address) 
        WebRequest request = base.GetWebRequest(address); 
        if (request is HttpWebRequest) 
            (request as HttpWebRequest).CookieContainer = container; 

        this.Headers.Add(HttpRequestHeader.ContentType, "application/json");

        return request; 

Now I can do tests like this:

public void LogOnTest()
    var webClient = new JsonWebClient();

    var logOnModel = new LogOnModel()
        Email = "john@doe.com",
        Password = "12345",
        RememberMe = true

    webClient.UploadString("http://localhost/WebSite/Membership/LogOn", DynamicJson.Serialize(logOnModel));

    var result = DynamicJson.Parse(webClient.DownloadString("http://localhost/WebSite/Product/BE33A625-63F3-4014-85E7-D306F00A5A7E"), UTF8Encoding.Unicode);

    Assert.AreEqual(result.Status, "ok");

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: