控制器Asp.Net之外我要起訂量的HttpContext在.NET核心1.0.0測試案例HttpContext的起訂量核心
這裏是我的代碼:
public async Task<string> Login(string email, string password)
{
var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false);
if (result.Succeeded)
{
return HttpContext.User.Identity.Name;
}
else
{
return "";
}
}
這裏是我的測試案例
[Fact]
public async Task Login()
{
ApplicationUser user = new ApplicationUser() { UserName = "[email protected]", Email = "[email protected]", Name = "siddhartha" };
await _userManager.CreateAsync(user, "[email protected]");
var userAdded = await _userManager.CreateAsync(user);
var result = await Login("[email protected]", "[email protected]");
Assert.Equal("siddhartha", result);
}
它去失敗,得到錯誤信息:
HttpCon文字不能爲空。
這裏是我的服務 - startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<PromactOauthDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().AddMvcOptions(x => x.Filters.Add(new GlobalExceptionFilter(_loggerFactory)));
}
我沒有注意到這一點,在第一,但是你的事實測試方法和你的實際登錄方法在同一個類中?測試如何直接調用Login而不創建Controller?如果你沒有創建控制器,你不能通過模擬。 –