Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Created November 23, 2012 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradoyler/4136617 to your computer and use it in GitHub Desktop.
Save bradoyler/4136617 to your computer and use it in GitHub Desktop.
Unit/Integration Testing MVC with RavenDb (using MS Test)
using System.Security.Principal;
namespace MyApp.Models.Authentication
{
public class CustomIdentity : GenericIdentity, ICustomIdentity
{
public CustomIdentity(string userId, string displayName)
: base(string.IsNullOrEmpty(displayName) ? string.Empty : displayName, "Forms")
{
UserId = userId;
}
#region Implementation of CustomIdentity
public string UserId { get; private set; }
#endregion
}
public class CustomPrincipal : GenericPrincipal
{
public CustomPrincipal(ICustomIdentity identity, string[] roles)
: base(identity, roles)
{
Identity = identity;
}
public new virtual ICustomIdentity Identity { get; private set; }
}
}
using System.Web.Mvc;
using CuttingEdge.Conditions;
using Moq;
using myApp.Models.Authentication;
namespace MyApp.Tests.Controllers
{
public static class ControllerUtilities
{
// Reference: http://nerddinnerbook.s3.amazonaws.com/Part12.htm
public static void SetUpControllerContext(ControllerBase controller,
string userId = null,
string displayName = null,
string[] roles = null)
{
Condition.Requires(controller);
// Some fake Authentication stuff.
var customIdentity = new CustomIdentity(userId, displayName);
var customPrincipal = new CustomPrincipal(customIdentity, roles);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(x => x.HttpContext.User).Returns(customPrincipal);
controller.ControllerContext = mockControllerContext.Object;
}
}
}
[TestClass]
public class GroupControllerTests
{
IDocumentStore _store;
[TestInitialize]
public void SetUp()
{
_store = new EmbeddableDocumentStore
{
RunInMemory = true
};
_store.Initialize();
Session = _store.OpenSession();
}
[TestMethod]
public void Adding_New_Group()
{
Group newGroup = new Group() { Name = "Test group" };
var target = new GroupsController(_store);
ControllerUtilities.SetUpControllerContext(target, "testGroup", "Test group", null);
RedirectToRouteResult result= target.Create(newGroup);
Assert.AreEqual("Index", result.RouteName);
// verify Group was successfully added to the database.
var createdGroup = session.Load<T>(newGroup.Id)
Assert.AreEqual(newGroup.Name, createdGroup.Name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment