如何用控制器编写XUNIT测试

时间:2018-05-02 12:00:58

标签: c# unit-testing asp.net-core-mvc xunit asp.net-core-identity

  1. 当我运行此代码输入有效的用户名和密码时,它仍然给我404.当我调试代码时,用户名显示为空。

  2. 如何编写单元测试来测试控制器的Login方法中的变量,以测试Identity是否为Null。(声明身份已添加)

  3. 我已经为模型状态编写了测试代码。

    我没有得到启动测试代码的任何线索。如果有人推高,那就太好了。

    public class AccountsControllers : Controller 
    {
        private readonly ApplicationContext appDbContext;
        private readonly IApplicationContext iappDbContext;
        private readonly UserManager<ApplicationUser> userManager;
    
        public AccountsControllers(ApplicationContext appDb 
            ,UserManager<ApplicationUser> um, 
            IApplicationContext iappdb)
        {
            userManager = um;
            appDbContext = appDb;
            iappDbContext = iappdb;
        }
    
        [Route("api/login")]
        [HttpPost
        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);
        }
    
    }
    

0 个答案:

没有答案