How to check Asp.Net UserManger CreateAsync ID

I am trying to check the failure conditions of my account controller. When I run the test in debug mode, I do not see the expected result. I expect to return a bad authentication result when it reaches a line of code to create an asynchronous user. however, in debug mode, it does not contain the error that I am providing, and the success property is true. according to this site: 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 , the way I do this, this should work.

What is the correct way to configure this test so that when UserManager.CreateAsync hits, it returns Failed IdentityResult?

The test I'm trying to run

    [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 method I'm trying to check

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

    }
+4
source share
1 answer

First of all, you are looking at the source of Identity 2.2-alpha1 - it has not yet been released. Better get a decompiler (I use DotPeek from Jetbrains) and decompile the assemblies that you use in your project.

Then you try to test the level too high. Extract your method to a class that is independent of your controllers:

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.
    }
}

In the controller, call this service:

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());
}

And check the user service separately from the controllers. Your tests will become much easier.

, . , , , .

+2

All Articles