title: How to test Asp.Net Identity UserManger CreateAsync
body: <p>I am trying to test for failure conditions of my Account controller.  When i run the test in debug mode, i am not seeing an expected result.  I am expecting to return a failed identity result when reach the line of code to create a user async.  however, in debug mode, it does not contain the error i provide it, and the success property is true.  according to this site: <a href="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" rel="nofollow">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</a>, the way i am going about this it "should" work.  </p>
  
  <p>what is the right way to setup this test so that when i hit UserManager.CreateAsync, it will return a Failed IdentityResult?</p>
  
  <p>Test i am trying to run</p>
  
  <pre><code>    [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&lt;IUserStore&lt;ApplicationUser&gt;&gt; userStore = new Mock&lt;IUserStore&lt;ApplicationUser&gt;&gt;();
          userStore.Setup(x =&gt; x.CreateAsync(It.IsAny&lt;ApplicationUser&gt;())).Returns(Task.FromResult(IdentityResult.Failed("Name " + model.Email + " already exists")));
          var passwordManager = userStore.As&lt;IUserPasswordStore&lt;ApplicationUser&gt;&gt;();
  
          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));
      }
  </code></pre>
  
  <p>web api method i am trying to test</p>
  
  <pre><code>    public async Task&lt;IHttpActionResult&gt; 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: &lt;a href=\"" + callbackUrl + "\"&gt;link&lt;/a&gt;");
  
                      return Ok();
                  }
              }
              return BadRequest(result.Errors.First());
          }
          catch (Exception ex)
          {
  
              return InternalServerError(ex);
          }
  
      }
  </code></pre>