mardi 24 mars 2015

MVC Unit testing [Authorize(Roles="Role")]

So I have been googling this for a couple of hours and I am yet to find a working solution.


Here are a couple of questions I have found that paint the picture of what I've been doing but none give me a working answer.


How do I unit test a controller method that has the [Authorize] attribute applied?


Unit testing ASP.Net MVC Authorize attribute to verify redirect to login page


What I am trying to do is to write a unit that that checks the [Authorise(Roles="Role")] attribute on my controller actually allows/denies access to the controller based on the current user belonging/not belonging to a specific role.


The code below always returns the view even when I set IsInRole to false hence I figure it is ignoreing the Authorise attribute.



[TestMethod]
public void Auth_User_Can_Access()
{
//this test mocks a user and submits it as part of the context to the controller
//Arrange
Mock<IPrincipal> mockP = new Mock<IPrincipal>();
mockP.SetupGet(p=>p.Identity.Name).Returns("UnitTesting");
mockP.Setup(p=>p.IsInRole("Role")).Returns(false); //"Role" is not the actual role name.

Mock<ControllerContext> mockC = new Mock<ControllerContext>();
mockC.SetupGet(p=>p.HttpContext.User).Returns(mockP.Object);
mockC.SetupGet(p=>p.HttpContext.Request.IsAuthenticated).Returns(true);

AppsController target = new AppsController(mock.Object);
target.ControllerContext = mockC.Object;

// Act
ViewResult result = target.Index() as ViewResult;

// Assert
Assert.IsNotNull(result);
}


I'm clearly missing something here.


For completeness here is the start of my Controller code also



[Authorize(Roles = "Role")]

public class AppsController : Controller
{
private IAppRepository db;

public AppsController (IAppRepository appRepository)
{
db = appRepository;
}

// GET: Apps

public ViewResult Index()
{
return View(db.Apps.ToList());
}

Aucun commentaire:

Enregistrer un commentaire