![](/img/trans.png)
[英]MVC4 WebSecurity.CurrentUserId returns -1 while User.Identity.Name is still valid
[英]mocking User.Identity.Name in MVC4
我正在嘗試為控制器(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),則測試可以正常完成。
誰能告訴我為什么?
這可能無法解決您的起訂量問題,但是對於它的價值, MvcContrib Test Helper對於模擬已登錄的用戶非常有用。
使用測試助手,您可以編寫如下代碼:
FakeIdentity FakeId = new FakeIdentity(UserName);
FakeUser = new FakePrincipal(FakeId, new[] { "Admin" });
Thread.CurrentPrincipal = FakeUser;
嘲笑用戶。 希望這可以幫助。
獲取用戶名時,代碼將引發異常。 User
從當前HTTP請求返回安全信息。 在測試期間,您沒有HTTP請求,因此此代碼引發異常。
這是此屬性的實現:
public IPrincipal User
{
get
{
if (HttpContext != null)
return HttpContext.User;
return null;
}
}
因此,如您所見,如果沒有HttpContext,它將返回null。 因此,您需要設置HttpContext並為測試提供模擬的IPrincipal
。 請參閱此處如何創建偽造的HttpContext。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.