Skip to content

Instantly share code, notes, and snippets.

@jamesantrobus
Last active January 3, 2016 20:49
Show Gist options
  • Save jamesantrobus/8517978 to your computer and use it in GitHub Desktop.
Save jamesantrobus/8517978 to your computer and use it in GitHub Desktop.
[TestFixture]
public class ControllerTests
{
[Test]
public void Foo()
{
CustomersController controller = new CustomersController().Testable()
.WithSession(Session)
.Authenticated(user => user.Foo = "bar");
controller.Request.Cookies.Add(new HttpCookie("foo"));
}
}
public static class TestableController
{
public static T Testable<T>(this T controller) where T : Controller
{
var cookies = new HttpCookieCollection();
var request = new Mock<HttpRequestBase>();
request.Setup(x => x.Cookies).Returns(() => cookies);
//setup headers and other fluff
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
return controller;
}
public static T Authenticated<T>(this T controller, Action<User> setUserProperties) where T : RavenController
{
var user = new User();
setUserProperties(user);
controller.RavenSession.Store(user);
controller.RavenSession.SaveChanges();
var authTicket = new FormsAuthenticationTicket(user.Id.ToString(), false, 1);
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
controller.Request.Cookies.Add(httpCookie);
return controller;
}
public static T WithSession<T>(this T controller, IDocumentSession session) where T : RavenController
{
controller.RavenSession = session;
return controller;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment