【发布时间】:2018-10-13 14:28:54
【问题描述】:
我正在为以下控制器编写 Xunit 测试。当我运行我的测试时,我得到了这个错误
object reference is notset to an instance of an object
这是我的测试代码
[Fact]
public async Task RegistrationTest()
{
ctrl = new AccountsControllers(context, userManager, jwtFactory, jwtoptions);
ctrl.ModelState.AddModelError("x", "Model error");
var mod = new RegistrationViewModel
{
Email = "johnmiller@sins.com"
};
IActionResult result = await ctrl.Register(mod);
// Assert.Equal(mod.Email, moe);
var viewresult = Assert.IsType<BadRequestObjectResult>(result);
}
但是,我成功地为上下文用户管理器创建了实例
var services = new ServiceCollection();
services.AddDbContext<ApplicationContext>(options => options
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Inventory;Trusted_Connection=True;ConnectRetryCount=0"));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationContext>();
var con = new DefaultHttpContext();
con.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = con });
var serviceProvider = services.BuildServiceProvider();
context = serviceProvider.GetRequiredService<ApplicationContext>();
userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
我不知道如何为 IJwtFactory 和 JwtIssuerOptions 创建
这是我的 Accounts 控制器构造函数
public AccountsControllers(ApplicationContext context, UserManager<ApplicationUser> userManager,
IJwtFactory jwtFactory, IOptions<JwtIssuerOptions> jwtoptions)
{
appDbContext = context;
this.userManager = userManager;
this.jwtFactory = jwtFactory;
jwtOptions = jwtoptions.Value;
serializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
}
这是帐户控制器中的登录方法
public async Task<IActionResult> Login([FromBody]LoginViewModel credentials)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
if (identity == null)
{
return BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
}
var response = new
{
id = identity.Claims.Single(c => c.Type == "id").Value,
auth_token = await jwtFactory.GenerateEncodedToken(credentials.UserName, identity),
expires_in = (int)jwtOptions.ValidFor.TotalSeconds
};
var json = JsonConvert.SerializeObject(response, serializerSettings);
return new OkObjectResult(json);
}
声明身份
public async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
{
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
{
// get the user to verifty
var userToVerify = await userManager.FindByNameAsync(userName);
if (userToVerify != null)
{
// check the credentials
if (await userManager.CheckPasswordAsync(userToVerify, password))
{
return await Task.FromResult(jwtFactory.GenerateClaimsIdentity(userName, userToVerify.Id));
}
}
}
return await Task.FromResult<ClaimsIdentity>(null);
}
【问题讨论】:
标签: asp.net-core-mvc jwt claims-based-identity xunit xunit.net