如何对依赖于c#中的身份验证的MVC控制器操作进行单元测试?

时间:2009-07-09 20:55:35

标签: c# asp.net-mvc unit-testing authentication

我想(在c#中)编写MVC控制器操作的单元测试,该操作可能返回一个视图或另一个视图,具体取决于请求是否经过身份验证。怎么办呢?

2 个答案:

答案 0 :(得分:34)

您可以模拟您的请求。这样的事情(Moq使用):

var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.IsAuthenticated).Returns(true); // or false

var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);

var controller = new YourController();
controller.ControllerContext = 
       new ControllerContext(context.Object, new RouteData(), controller);

// test

ViewResult viewResult = (ViewResult)controller.SomeAction();

Assert.True(viewResult.ViewName == "ViewForAuthenticatedRequest");

答案 1 :(得分:16)

使用模拟和依赖注入。以下假设您正在检查它是否已通过身份验证,然后访问用户对象以获取用户的ID。使用RhinoMocks

// mock context variables
var username = "user";
var httpContext = MockRepository.GenerateMock<HttpContextBase>();
var request = MockRepository.GenerateMock<HttpRequestBase>();
var identity = MockRepository.GenerateMock<IIdentity>();
var principal = MockRepository.GenerateMock<IPrincipal>();

httpContext.Expect( c => c.Request ).Return( request ).Repeat.AtLeastOnce();
request.Expect( r => r.IsAuthenticated ).Return( true ).Repeat.AtLeastOnce();
httpContext.Expect( c => c.User ).Return( principal ).Repeat.AtLeastOnce();
principal.Expect( p => p.Identity ).Return( identity ).Repeat.AtLeastOnce();
identity.Expect( i => i.Name ).Return( username ).Repeat.AtLeastOnce();

var controller = new MyController();
// inject context
controller.ControllerContext = new ControllerContext( httpContext,
                                                      new RouteData(),
                                                      controller );

var result = controller.MyAction() as ViewResult;

Assert.IsNotNull( result );

// verify that expectations were met
identity.VerifyAllExpectations();
principal.VerifyAllExpectations();
request.VerifyAllExpectations();
httpContext.VerifyAllExpectations();