5

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.

2

3 Answers 3

8

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);
    }
0

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

0

There is a third option, that is using Xania.AspNet.Simulator

first prepare the controller action

// arrange
var controllerAction = new AccountController().Action(c => c.ChangePassword())
    .Authenticate(<username>, <roles>);

next you have two options depending on your implementation,

first scenario, if you return an HttpUnauthorizedResult, i.e. when using Authorize attribute or when you override AuthorizeCore of your controller, then you could test it like following, in which case the actual action method is not invoked.

// act, assert
controllerAction.Authorize().Should().BeNull();

Second scenario is when you actually validate the user inside the action method:

// act
var result = controllerAction.Execute();
// assert
result.ActionResult.Should().NotBeOfType<HttpUnauthorizedResult>();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.