MVC单元测试[授权(角色=“角色”)]

时间:2015-03-25 05:15:57

标签: asp.net-mvc unit-testing

所以我一直在谷歌上搜索几个小时,我还没有找到一个有效的解决方案。

以下是我发现的几个问题,描绘了我一直在做的事情但却没有给我一个合适的答案。

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

我要做的是编写一个单元来检查我的控制器上的[Authorize(Roles =“Role”)]属性实际上允许/拒绝基于属于/不属于的当前用户访问控制器具体的角色。

下面的代码总是返回视图,即使我将IsInRole设置为false,因此我认为它忽略了Authorize属性。

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

我在这里显然遗漏了一些东西。

为了完整性,这里是我的Controller代码的开始

[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());
    }

1 个答案:

答案 0 :(得分:1)

您可以在Xania.AspNet.Simulator

的帮助下编写单元测试
new AppsController(appRepo).Action(c => c.Index())
    .Authenticate("user1", new []{"Role"})
    .Authorize().Should().BeNull(); // authorized

new AppsController(appRepo).Action(c => c.Index())
    .Authenticate("user1", new []{"Dummy"})
    .Authorize().Should().BeOfType<HttpUnauthorizedResult>();  // not authorized

有关详细信息,请参阅http://www.codeproject.com/Tips/850277/ASP-NET-MVC-End-to-End-Integration-Testing