Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created July 10, 2014 12:58
Show Gist options
  • Save jarrettmeyer/7d49add3b117e169637a to your computer and use it in GitHub Desktop.
Save jarrettmeyer/7d49add3b117e169637a to your computer and use it in GitHub Desktop.
Unit testing a controller
// Version 0: Nope.
public class SomeController
{
public object Get(string story, string view)
{
// Unit test blows up on the following line because there
// is no Request (NullReferenceException) from within a
// unit test.
var queryString = Request.RequestUri.ParseQueryString();
// snip
}
}
// Version 1: This can be unit tested now, so it's better insofar as my tests
// can pass.
public class SomeController
{
public bool HasRequestUri
{
get { return Request != null && Request.RequestUri != null; }
}
public object Get(string story, string view)
{
// No exception thrown if the Request is null.
var queryString = GetQueryString();
// snip
}
private static NameValueCollection GetQueryString()
{
return HasRequestUri ? Request.RequestUri.ParseQueryString() : new NameValueCollection();
}
}
// Version 2: I stil can't test that different things should happen based on values
// that might be in the query string, so I need to expose the query string.
public class SomeController
{
private NameValueCollection queryString;
public bool HasRequestUri
{
get { return Request != null && Request.RequestUri != null; }
}
public NameValueCollection QueryString
{
get
{
if (queryString != null)
return queryString;
queryString = HasRequestUri ? Request.RequestUri.ParseQueryString() : new NameValueCollection();
return queryString;
}
set { queryString = value; }
}
public object Get(string story, string view)
{
// Now use QueryString instead of queryString everywhere in this method.
// snip
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment