2011-08-10 36 views
0

我試圖運行單元測試,因爲它使用集成的Windows身份驗證來驗證當前用戶,因此依賴於Web實例。當我運行測試時,它並沒有激活預期的Web實例,但我需要它來讓任何測試成功。任何人有任何想法如何做到這一點?連接本地IIS Web實例的單元測試

回答

1

好的,我最終得到了這個工作。你必須模擬HttpContextBase(這是優於我聽到的HttpContext),然後設置從模擬對象返回的IPrincipal。我將給出完整的代碼清單,以便您瞭解:

[TestInitialize] 
public void SetUp() 
{ 
    userRepositoryMock = new Mock<IUserRepository>(); 
    controller = new AccountController(userRepositoryMock.Object); 

    httpContextMock = new Mock<HttpContextBase>(); 
    IPrincipal fakeUser = new GenericPrincipal(new GenericIdentity("[email protected]", "Forms"), null); 
    httpContextMock.Setup(x => x.User).Returns(fakeUser); 

    var context = new Mock<HttpContextBase>(); 
    var request = new Mock<HttpRequestBase>(); 
    var response = new Mock<HttpResponseBase>(); 
    var session = new Mock<HttpSessionStateBase>(); 
    var server = new Mock<HttpServerUtilityBase>(); 
    var identity = new Mock<IIdentity>(); 

    request.Setup(req => req.ApplicationPath).Returns("~/"); 
    request.Setup(req => req.AppRelativeCurrentExecutionFilePath).Returns("~/"); 
    request.Setup(req => req.PathInfo).Returns(string.Empty); 
    response.Setup(res => res.ApplyAppPathModifier(It.IsAny<string>())) 
     .Returns((string virtualPath) => virtualPath); 
    identity.SetupGet(ident => ident.IsAuthenticated).Returns(true); 
    context.Setup(ctx => ctx.Request).Returns(request.Object); 
    context.Setup(ctx => ctx.Response).Returns(response.Object); 
    context.Setup(ctx => ctx.Session).Returns(session.Object); 
    context.Setup(ctx => ctx.Server).Returns(server.Object); 
    context.Setup(ctx => ctx.User).Returns(fakeUser); 

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