模拟HTTPContext的全局范围 - CloudService项目?

时间:2017-05-29 18:44:53

标签: c# unit-testing azure moq azure-web-roles

我正在尝试为我的WebRole项目设置单元测试框架。我创建了一个模拟HTTP上下文并将其附加到我试图测试的控制器上:

var fakeHttpContext = new Mock<HttpContextBase>();
var fakeIdentity = new GenericIdentity(username);
var principal = new GenericPrincipal(fakeIdentity, null);

fakeHttpContext.Setup(t => t.User).Returns(principal);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);

var controller = new HomeController();
controller.ControllerContext = controllerContext.Object;

我的问题是,不是将模拟上下文附加到一个控制器,我可以在全局范围内模拟项目的HTTP上下文,因此所有控制器和实用程序类都可以访问模拟HTTP上下文吗?

//Mock Context is attached to this controller. When Membership provider is accessed 
//from inside the controller it works fine. However when Membership Provider 
//is used from outside the Controller it returns null. 
public void controlerMethodinHomeController()
{ 
    //Returns Null
    var userID = Utility.GetUserId();

    //Returns valid UserID
    var userID = Membership.GetUser(User.Identity.Name).ProviderUserKey;
}

///Utility Class
public static Guid GetUserId()
{
  var user = Membership.GetUser();
  return user.ProviderUserKey
}

0 个答案:

没有答案