2013-09-25 82 views
20

我有代碼,這會消耗HttpContext如何嘲笑HttpContext.User.Identity.Name在Asp.Net MVC 4

public ActionResult Index() 
{ 

    var currentUser=HttpContext.User.Identity.Name; 
    ...... 

} 

控制器在試圖寫使用NUnit這樣

[Test] 
public void CanDisplayRequest() 
{ 
    //Act 
    var result= (ViewResult)_requestController.Index(); 

    //Assert 
    Assert.IsInstanceOf<OrderRequest>(resut.Model); 
} 
測試

測試將失敗,因爲它找不到HttpContext

所以,我怎麼能嘲笑HttpContext.Current.User.Identity.Name

我使用起訂量爲懲戒

回答

41

可以初始化與假貨主要假的情況下你的控制器如下圖所示

 var fakeHttpContext = new Mock<HttpContextBase>(); 
     var fakeIdentity = new GenericIdentity("User"); 
     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);   

     _requestController = new RequestController(); 

     //Set your controller ControllerContext with fake context 
     _requestController.ControllerContext = controllerContext.Object; 
+1

難道你們也有做同樣的事情的一個片段,但使用的Microsft假貨/測試而不是任何其他第三方測試框架? –