单元测试 – 如何测试Asp.Net Identity UserManger CreateAsync

我正在尝试测试我的帐户控制器的故障情况.当我在调试模式下运行测试时,我没有看到预期的结果.我希望在到达代码行时返回失败的身份结果以创建用户异步.但是,在调试模式下,它不包含我提供的错误,并且success属性为true.根据这个网站:
https://www.symbolsource.org/MyGet/Metadata/aspnetwebstacknightly/Project/Microsoft.AspNet.Identity.Core/2.0.0-rtm-140226/Release/Default/Microsoft.AspNet.Identity.Core/Microsoft.AspNet.Identity.Core/IdentityResult.cs?ImageName=Microsoft.AspNet.Identity.Core,我这样做的方式“应该”起作用.

设置此测试的正确方法是什么,以便在我点击UserManager.CreateAsync时,它将返回失败的IdentityResult?

测试我想跑

    [TestMethod]
    public async Task AccountController_Post_register_valid_model_account_creation_fails_returns_exception_result()
    {
        // arrange
        RegisterApiModel model = new RegisterApiModel
        {
            BusinessType = BusinessType.Architect,
            City = "asdf",
            CompanyName = "asdf",
            Email = "asdf@asdf.com",
            FirstName = "asdf",
            JobTitle = "asdf",
            LastName = "asdf",
            OperatingDistance = 123,
            Phone = "1231231234",
            Password = "12345678",
            PostalCode = "asdf",
            PrimaryContactName = "asdf",
            PrimaryContactPhone = "1231231234",
            PrimaryContactTitle = "asdf",
            StateId = 2
        };


        // create http request
        var config = new HttpConfiguration();
        var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost.com/api/Account/Register");
        var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
        var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "Companies" } });

        // mock userstore
        Mock<IUserStore<ApplicationUser>> userStore = new Mock<IUserStore<ApplicationUser>>();
        userStore.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>())).Returns(Task.FromResult(IdentityResult.Failed("Name " + model.Email + " already exists")));
        var passwordManager = userStore.As<IUserPasswordStore<ApplicationUser>>();

        ApplicationUserManager um = new ApplicationUserManager(userStore.Object);
        um.PasswordValidator = pwValidator;

        AccountController controller = new AccountController(um);
        controller.ControllerContext = new HttpControllerContext(config, routeData, request);
        controller.Request = request;
        controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

        // act
        var result = await controller.Register(model);

        // assert
        result.ShouldBeType(typeof(ExceptionResult));
    }

web api方法我试图测试

    public async Task<IHttpActionResult> Register([FromBody]RegisterApiModel model)
    {
        try
        {
            var company = new Company
            {
                Name = model.CompanyName,
                CreateDate = DateTime.Now,
                SubscriptionStatus = SubscriptionStatus.Free,
                Address1 = model.Address1 ?? string.Empty,
                Address2 = model.Address2 ?? string.Empty,
                City = model.City,
                StateId = model.StateId,
                PostalCode = model.PostalCode,
                BusinessType = model.BusinessType.Value,
                OperatingDistance = model.OperatingDistance.Value,
                Phone = PhoneNumber.ToStorage(model.Phone),
                Fax = model.Fax == null ? string.Empty : PhoneNumber.ToStorage(model.Fax),
                PrimaryContactName = model.PrimaryContactName,
                PrimaryContactPhone = PhoneNumber.ToStorage(model.PrimaryContactPhone),
                PrimaryContactTitle = model.PrimaryContactTitle

            };

            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Company = company, JobTitle = model.JobTitle };

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                // make user a company admin
                user.Claims.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim { ClaimValue = "Admin", ClaimType = "http://bidchuck.com/company/role", UserId = user.Id });
                result = await UserManager.UpdateAsync(user);
                if (result.Succeeded)
                {
                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Link("Default", new { controller = "Account", action = "ConfirmEmail", userId = user.Id, code = code });

                    await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");

                    return Ok();
                }
            }
            return BadRequest(result.Errors.First());
        }
        catch (Exception ex)
        {

            return InternalServerError(ex);
        }

    }

最佳答案 首先,您正在寻找身份2.2-alpha1的来源 – 它尚未发布.最好得到反编译器(我使用Jetbrains的DotPeek)并反编译你在项目中使用的程序集.

然后你试图在太高的水平上进行测试.将您的方法解压缩到独立于您的控制器的类:

UserService
{
    public IdentityResult CreateUser(RegisterApiModel model, String urlCallback)
    {
        // don't forget to add generated code and userId as parameters into url
        // do your user creation.
    }
}

在您的控制器中调用此服务:

public async Task<IHttpActionResult> Register([FromBody]RegisterApiModel model)
{
    var urlCallbac = Url.Link("Default", new { controller = "Account", action = "ConfirmEmail" });
    var result = await userService.CreateUserAsync(model, urlCallback);

    if (result.Succeeded)
    {
        return Ok();
    }

    return BadRequest(result.Errors.First());
}

并与控制器分开测试用户服务.您的测试将变得更加简单.

目前很难说你为什么得到这个结果.可能没有完全设置模拟来完成需要完成的工作.

点赞