[英]Test an Asp.Net Controller action method which uses User.Identity.Name?
對於Asp.Net控制器操作方法,我具有以下測試方法。
[TestMethod]
public void Get()
{
var controller = new MyController();
var result = controller.GetAListOfRecords();
Assert.IsNotNull(result);
Assert.IsTrue(result.Count() > 0);
}
動作是
[Authorize(Roles = "Users")]
public IQueryable<MyModel> GetAListOfRecords()
{
var user = User.Identity.Name; // null when called from the test method
var q = from t in ........
select t;
return return string.IsNullOrEmpty(user) ? Enumerable.Empty<MyModel>().AsQueryable() : q;
}
但是, var user = User.Identity.Name
將不會在測試類中獲得當前用戶名(實際上將為其分配一個空字符串)。 可以在測試方法中設置user
嗎?
更新:我在測試類中嘗試了以下操作,但是.....Identity.Name
是只讀的。
controller.RequestContext.Principal.Identity.Name = @"mdynycmas\wangyi";
實際上,您是在Controller對象上使用User屬性。 此屬性使用基礎HttpContext.Current。 您需要模擬HttpContextBase並返回一個測試用戶,例如,參見如何使用moq模擬Controller.User 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.