views:

408

answers:

3

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.

A: 

If using TDD your tests should only test the code in question, all other associated objects should be mocks/fakes

among others, you'll need a mock security provider that can simulate the user cases you require to test (guest, user1, user2, admin etc)

When you make a blank MVC project with current MVC RC you get a basic test framework with mock security providers (membership/roles etc). They need some fleshing out, but give the basic design

TFD
+6  A: 

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);
    }
Scott Hanselman