![](/img/trans.png)
[英]Web API 2: ApiController.User property not matching Thread.CurrentPrincipal
[英]Unit Test Web Api Controller fake ApiController.User with custom Identity doesn't work
我目前正在使用Web API v5.2.2,我正在為其中一個控制器編寫單元測試代碼。 我遇到的問題發生在ApiController.User部分。
我有一個用戶實現的IIdentity接口的自定義標識:
public class CustomIdentity : IIdentity
{
//Constructor and methods
}
正常用法中的HttpRequest中設置了CustomIdentity。 但由於我只測試單元測試中的查詢功能,我只是調用控制器及其方法而不是發送請求。
因此,我必須將用戶標識插入到線程中,我嘗試了以下方法:
var controller = new AccountsController(new AccountUserContext());
第一次嘗試:
controller.User = new ClaimsPrincipal(new GenericPrincipal(new CustomIdentity(user), roles.Distinct().ToArray()));
第二次嘗試:
IPrincipal principal = null;
principal = new GenericPrincipal(new CustomIdentity(user), roles.Distinct().ToArray());
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
但是,我從這兩次嘗試中得到了這個錯誤:
你調用的對象是空的。
我發現用戶身份在線程中保持為空。
以前有人試過這種方法嗎? 謝謝你的建議!
你說
正常用法中的HttpRequest中設置了CustomIdentity。
您是否在組裝測試時向控制器附加請求?
在這里查看示例
[TestMethod]
public void QueryAccountControllerTest()
{
// Arrange
var user = "[Username Here]"
var controller = new AccountsController(new AccountUserContext());
//Set a fake request. If your controller creates responses you will need tis
controller.Request = new HttpRequestMessage {
RequestUri = new Uri("http://localhost/api/accounts")
};
controller.Configuration = new HttpConfiguration();
controller.User = new ClaimsPrincipal(new CustomIdentity(user));
// Act
... call action
// Assert
... assert result
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.