2016-12-16 68 views
1

控制器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))); 
    } 
+0

我沒有注意到這一點,在第一,但是你的事實測試方法和你的實際登錄方法在同一個類中?測試如何直接調用Login而不創建Controller?如果你沒有創建控制器,你不能通過模擬。 –

回答

0

我認爲錯誤是在SignInManager的構造空校驗。我不知道你是如何爲你的測試構建你的SignInManager的,所以我不能確定你是否通過了一些東西,但我懷疑不是。

如果是這種情況,請創建一個IHttpContextAccessor模擬器並設置HttpContext屬性以返回一個新的DefaultHttpContext(),然後將該模擬對象傳遞到SignInManager中。

+0

根據你的建議,我嘗試過但仍然無法工作。 @Runesun –

+0

然後你需要提供更多的代碼。我無法告訴你如何在提供的代碼中建立管理器依賴關係(即SignInManager)。 –

2

不使用控制器。我有.net核心moq HttpContext。而在倉庫中使用的HttpContext

註冊的HttpContext在這樣

public void ConfigureServices(IServiceCollection services) 
{  
     var authenticationManagerMock = new Mock<AuthenticationManager>(); 
     var httpContextMock = new Mock<HttpContext>(); 
     httpContextAccessorMock.Setup(x => x.HttpContext.User.Identity.Name).Returns("Siddhartha"); 
     httpContextMock.Setup(x => x.Authentication).Returns(authenticationManagerMock.Object); 
     var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); 
     httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object); 
     var httpContextMockObject = httpContextAccessorMock.Object; 
     services.AddScoped(x => httpContextAccessorMock); 
     services.AddScoped(x => httpContextMockObject); 
     serviceProvider = services.BuildServiceProvider(); 
} 

測試用例項目,然後你會得到HttpContext.User.Identity.Name =悉達多

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 ""; 
    } 
}