I've been writing tests for my domain objects for some time now, but I'm still not quite sure how to go about testing for security in my web project. Certain users in certain environments can access certain properties of my models etc, but how would you go about testing this? Right now, I'm basing it on the current authenticated user, but how would I go about injecting a fake authentication provider?
This is probably a dumb question, but if anyone can help me get out of the testing dark ages, it would be much appreciated.
MVC provides a lot of infrastructure support for Forms Authentication. Forms authentication is highly customizable, you can customize everything from the sign in form, to where the credentials are stored and how those credentials are validated. Forms Authentication in ASP.NET relies on cookies by default.
That link is ONE way, but it's nicer to use a Mock:
Mock<ControllerContext> MockContext(string userName)
{
var mockContext = new Mock<ControllerContext>();
// mock an authenticated user
mockContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
mockContext.SetupGet(p => p.HttpContext.User.Identity.IsAuthenticated).Returns(true);
return mockContext;
}
[TestMethod]
public void DinnersController_Delete_Should_Fail_With_InvalidOwner_Given_Wrong_User()
{
//set by default
var mockContext = MockContext("scottha");
// mock an authenticated user
_dinnerController.ControllerContext = mockContext.Object;
ViewResult result = _dinnerController.Delete(1, "") as ViewResult;
Assert.AreEqual("InvalidOwner", result.ViewName);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With