Created
September 18, 2013 14:27
-
-
Save sharpjs/6609988 to your computer and use it in GitHub Desktop.
Mocking controller context in ASP.NET MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Security.Principal; | |
using System.Web; | |
using System.Web.Mvc; | |
using System.Web.Routing; | |
using Moq; | |
namespace SharpJS.Web.Testing | |
{ | |
public static class ControllerTestExtensions | |
{ | |
public static TController WithContext<TController> | |
(this TController controller) | |
where TController : Controller | |
{ | |
if (controller.ControllerContext == null) | |
{ | |
var context = new Mock<HttpContextBase> | |
{ DefaultValue = DefaultValue.Mock } | |
.Object; | |
Mock.Get(context) | |
.Setup(c => c.Items).Returns(new Hashtable()); | |
// More mocking how-to here: | |
// http://blog.spontaneouspublicity.com/unit-testing-the-mvc4-account-controller | |
controller.ControllerContext = new ControllerContext | |
(context, new RouteData(), controller); | |
} | |
return controller; | |
} | |
public static TController AsUser<TController> | |
(this TController controller, params string[] roles) | |
where TController : Controller | |
{ | |
var identity = new GenericIdentity("user@example.net", "test"); | |
var principal = new GenericPrincipal(identity, roles); | |
controller.WithContext().HttpContext.User = principal; | |
return controller; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment