<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>{ Code: Impossible } &#187; Unit Testing</title>
	<atom:link href="http://codeimpossible.com/tag/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://codeimpossible.com</link>
	<description>this = HowI.Roll();</description>
	<lastBuildDate>Thu, 29 Jul 2010 02:58:45 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Testing JsonResult in Asp.net MVC</title>
		<link>http://codeimpossible.com/2009/03/16/testing-jsonresult-in-aspnet-mvc/</link>
		<comments>http://codeimpossible.com/2009/03/16/testing-jsonresult-in-aspnet-mvc/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 00:23:22 +0000</pubDate>
		<dc:creator>Jared</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://codeimpossible.com/?p=340</guid>
		<description><![CDATA[So lately I&#8217;ve been working on a project using Asp.net MVC and TDD to build a web 2.0 application. It&#8217;s a twitter-like application that I started a while ago but due to my failure to test everything I lost about 99% of my work and had to start over from scratch.
But this was sort of [...]]]></description>
			<content:encoded><![CDATA[<p>So lately I&#8217;ve been working on a project using Asp.net MVC and TDD to build a web 2.0 application. It&#8217;s a twitter-like application that I started a while ago but due to <a href="" title="Test Everything!">my failure to test everything</a> I lost about 99% of my work and had to start over from scratch.</p>
<p>But this was sort of a good thing because it gave me a chance to revisit a lot of things that I wasn&#8217;t very happy with the first time around. I just got done adding the ability for users to post new messages via AJAX.</p>
<p>In the first version of the application a user would type their status into a textbox, click submit and the page would refresh with their new message at the top of their user wall. Although functional this wasn&#8217;t exactly very &#8220;web 2.0&#8243;-ish.</p>
<p>My controller will have an action called Index that takes two parameters, the message the users is posting and the tags associated with that message. m_UserService, and m_MessageService are private objects, that interact with the database.</p>
<pre class="brush:csharp">
[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string message, string[] tags)
{

	var messageOwner = this.m_UserService
		.GetByUserName(User.Identity.Name);

	var messageObj = new Message()
	{
		Owner = new User()
		{
			Identifier = messageOwner.Identifier,
			UserName = messageOwner.UserName,
			Email = messageOwner.Email,
			RealName = messageOwner.RealName,
			IsModerator = messageOwner.IsModerator
		},
		Body = message,
		CreatedOn = DateTime.Now,
		IsReply = message.StartsWith("@")
	};

	this.m_MessageService.Post(messageObj);

	return Json(messageObj);
}
</pre>
<p>The JsonResult will be serialized/deserialized by the MVC framework when the code is run in a web project or IIS but I need to be able to test this as part of our build process.</p>
<p><i>* NOTE: For those of you who might be thinking &#8220;how do we get around the authorization&#8221;? I&#8217;ll answer that in a later post (or you can <a href="http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx">check out Scott Hanselmans blog for the solution</a>).</i></p>
<p>Ideally I wanted to do something like the following in my test:</p>
<pre class="brush:csharp">
	Assert.AreEqual("some text", jsonObject.someproperty);
</pre>
<p>But since C# is a type-safe language this isn&#8217;t easily doable. However, utilizing an extension method and the JavaScriptSerializer in System.Web.Script.Serialization we can come pretty close:</p>
<pre class="brush:csharp">
	Assert.AreEqual("some text", jsonObject["someproperty"]);
</pre>
<p>Here is the code I used to achieve this (This code depends on <a href="http://code.google.com/p/moq/">Moq v3.0.108.5 which you can download here</a>):</p>
<pre class="brush:csharp">
using System;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;

using Moq;

public static class JsonResultExtensions
{

	public static T Deserialize&lt;T>(this JsonResult json,
		Controller controller)
	{

		var jsonSB = new StringBuilder();

		var httpResponseMock =
			new Mock&lt;httpResponseBase>();

		httpResponseMock.Setup(mock => {
			mock.Write(It.IsAny&lt;string>());
		}).Callback&lt;string>((s) => {
			jsonSB.Append(s);
		});

		var httpContextMock =  new Mock&lt;httpContextBase>();

		httpContextMock.Setup(mock => mock.Response)
			.Returns(httpResponseMock.Object);

		controller.ControllerContext
			.HttpContext = httpContextMock.Object;

		jsonResult.ExecuteResult(
			controller.ControllerContext);

		return new JavaScriptSerializer()
			.Deserialize&lt;T>(jsonSB.ToString());
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://codeimpossible.com/2009/03/16/testing-jsonresult-in-aspnet-mvc/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
