2012-11-09 57 views
0

我試圖寫在控制器的我的方法之一(MVC4)測試。我使用Moq。在測試方法中,我爲我的存儲庫創建了一個模擬器,如下所示:嘲諷User.Identity.Name在MVC4

Mock<ISurveyRepository> mock = new Mock<ISurveyRepository>(); 

並繼續模擬存儲庫調用。那些第一個是:

int userId = repository.GetUserId(User.Identity.Name); 

所以我將它添加到我的測試方法:

mock.Setup(y => y.GetUserId("testName")).Returns(1); 

可惜的是這行代碼給我:

System.NullReferenceException: Object reference not set to an instance of an object. 

如果我刪除上面的行從我的控制器,並使用靜態值(int userId = 1)測試完成罰款。

有誰能告訴我爲什麼?

回答

0

你的代碼拋出異常,當你得到的用戶名。 User從當前HTTP請求中返回安全信息。在測試期間,您沒有HTTP請求,因此此代碼會引發異常。

下面是這個屬性的實現:

public IPrincipal User 
{ 
    get 
    { 
     if (HttpContext != null)    
      return HttpContext.User; 

     return null; 
    } 
} 

所以,你看,沒有的HttpContext返回null。因此,您需要設置HttpContext併爲您的測試提供模擬的IPrincipal。請參閱here如何創建假的HttpContext。

1

這可能不是解決您的起訂量的問題,而是什麼它的價值,MvcContrib Test Helper是嘲諷登錄的用戶非常有用。

使用測試助手,你可以這樣寫代碼:

FakeIdentity FakeId = new FakeIdentity(UserName); 
FakeUser = new FakePrincipal(FakeId, new[] { "Admin" }); 
Thread.CurrentPrincipal = FakeUser; 

嘲笑用戶。希望這可以幫助。