Search code examples
c#asp.netauthenticationasp.net-identity

UserManager.CreateAsync hangs on execution from Unit Test but not Postman


I'm really baffled right now. So I've been working on a Web API and unit testing the project as I'm going and just made a change with a lot of controllers recently but completely left the AccountController untouched. In my AccountController I have the function Register() which has been working great for the past 2 months everytime I test. Now all of a sudden though when I enter Register and call,

IdentityResult result = await UserManager.CreateAsync(user, model.Password);

My program hangs and won't come back. I tested some things out and this only happens when called from my unit test (Which also hasn't changed) and when I call Register from Postman with the exact same JSON it works just fine.

Register API Function

// POST api/Account
[AllowAnonymous]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, Active = true, CreationDate = DateTime.Now };

    IdentityResult result = await UserManager.CreateAsync(user, model.Password);

    if (!result.Succeeded)
    {
        return GetErrorResult(result);
    }

    return Ok();
}

Test Function

[TestMethod]
public void Register_Pass()
{
    // Arrange & Act
    var db = new WizardSwearsDB();

    new DBCleanup().RemoveRegisteredUser(userName);
    string apiCall = "";
    new
    {
        UserName = userName,
        Email = email,
        Password = password,
        ConfirmPassword = password
    }.Post(baseUrl + apiCall);

    var user = (from u in db.AspNetUsers
                where u.UserName == userName
                select u).FirstOrDefault();

    // Assert
    Assert.IsNotNull(user);
    Assert.AreEqual(userName, user.UserName);
}

JSON Post Functionality

public static void Post(this object obj, string url, string securityToken = null)
{
    var request = WebRequest.Create(url);
    obj.Request<string>(url, postJsonRequestBuilder, null, securityToken);
}

private static Func<string, object, string, WebRequest> postJsonRequestBuilder = (url, o, st) => jsonRequestBuilder(url, o, "POST", st);

private static Func<string, object, string, string, WebRequest> jsonRequestBuilder = delegate(string url, object obj, string method, string securityToken)
{
    WebRequest request = WebRequest.Create(url);
    if (!string.IsNullOrEmpty(securityToken)) request.Headers.Add("Authorization", string.Format("Bearer {0}", securityToken));
    request.Method = method;
    if (obj != null)
    {
        request.ContentType = "application/json";
        var payload = encoding.GetBytes(JsonConvert.SerializeObject(obj));
        request.ContentLength = payload.Length;
        using (var stream = request.GetRequestStream())
        {
            stream.Write(payload, 0, payload.Length);
        }
    }
    return request;
};

Remove Registered User Function and Remove Employee Function

public void RemoveRegisteredUser(string userName)
{
    // Open up a connection to the database
    var db = new WizardSwearsDB();

    // Get the user from the ASPNetUsers table
    var dbUserASP = (from b in db.AspNetUsers
                    where b.UserName == userName
                    select b).FirstOrDefault();


    // Remove the user from both tables and save changes
    if (dbUserASP != null)
    {
        db.AspNetUsers.Remove(dbUserASP);
        db.SaveChanges();
    }

    RemoveEmployee(userName);
}

public void RemoveEmployee(string userName)
{
    // Open up a connection to the database
    var db = new WizardSwearsDB();

    // Get the user from the ASPNetUsers table
    var employee = (from b in db.Employees
                    where b.UserName == userName
                    select b).FirstOrDefault();

    // Remove the user from both tables and save changes
    if (employee != null)
    {
        db.Employees.Remove(employee);
        db.SaveChanges();
    }
}

So none of these functions have changed at all, and my guess is it has to do something with await, but I just can't figure out why it is behaving this way.


Solution

  • Just solved the problem. Did a full restart of my computer and Visual Studio and voila. On a side note, anyone familiar with why this fixed the issue? Maybe just a Visual Studio bug?