所以我一直在Google上搜索几个小时,但我还没有找到工作解决方案。MVC单元测试[授权(角色=“角色”)]
这里有几个问题,我发现画的是我一直在做的事情,但没有给我一个工作答案。
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
我所试图做的是写一个检查的一个单元[授权(角色=“角色”)]我控制器上属性实际上可允许/拒绝的访问控制器基于当前用户属于/不属于特定角色。
即使我将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);
}
我很明显在这里丢失了一些东西。
为了完整这里是我的控制器代码的开始也
[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());
}
.Ashenticated.Returns(False)也没有区别。 – codemonkeytony 2015-03-25 05:26:02
如果您已按照链接中的链接进行操作,那么您会得到正确的答案:http://stackoverflow.com/a/670838/126014 – 2015-03-25 06:37:59
@MarkSeemann您能否详细说明一下? “我在这里显然错过了一些东西。” – codemonkeytony 2015-03-25 21:23:21