2016-12-16 66 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 ""; 
    } 
}