用于检查用户角色的ActionResult的NUnit测试

时间:2016-02-19 17:31:17

标签: asp.net .net asp.net-mvc unit-testing nunit

我目前是ASPNET MVC框架的新手,我想使用NUnit进行一些单元测试,我遇到了困难。

我的问题是我有一个控制器,大多数ActionResults方法都在其中检查当前登录用户是否属于某些角色,现在我的问题是如何使用{{1登录所以那些NUnit测试可以是携带的,否则它们将返回ActionResults

以下是nullexception方法的一些代码,可以为您提供有关情况的概述。您是否也可以指出我可以测试哪种东西?

Index()

提前谢谢你。

2 个答案:

答案 0 :(得分:1)

对您的控制器进行一些假设,并使用本演练Walkthrough: Using TDD with ASP.NET MVC中的一个想法,我想您可以试试这个

[TestClass]
public class ControllerUnitTest {

    [TestMethod]
    public void ControllerIndexTest() {
        // Arrange
        var username = "[Test_Username_Here]";
        string[] roles = new[] { "FakeRoleId1", "FakeRoleId2" };
        var controller = new CollorsController(new FakeDbContext());
        controller.ControllerContext = new ControllerContext() {
            Controller = controller,
            RequestContext = new RequestContext(new MockHttpContext(username, roles), new RouteData())
        };

        // Act
        var actionResult = controller.Index();
        var viewResult = actionResult as ViewResult;

        // Assert
        Assert.IsNotNull(viewResult);
        Assert.IsTrue(viewResult.ViewData.ContainsKey("Colours"));
    }

    private class MockHttpContext : HttpContextBase {
        private readonly IPrincipal user;

        public MockHttpContext(string username, string[] roles = null) {
           var identity = new GenericIdentity(username, string.Empty);
           var principal = new GenericPrincipal(identity, roles ?? new string[] { });
           user = principal;
        }

        public override IPrincipal User {
            get {
                return user;
            }
            set {
                base.User = value;
            }
        }
    }
}    

答案 1 :(得分:0)

您可以使用Typemock Isolator轻松模拟HttpContext:

var username = "[Test_Username_Here]";
string[] roles = new[] { "FakeRoleId1", "FakeRoleId2" };
var fake = Isolate.Fake.AllInstances<HttpContextBase>();
var user = new ClaimsPrincipal(new GenericPrincipal(username, roles ?? new string[] { }));
Isolate.WhenCalled(() => fake.User).WillReturn(user);