lundi 27 avril 2015

Why does my Web Service Function work accessing SQL (via Entity/Identity) when called w/ Fiddler or another application, but fails in unit testing?

I have an AccountController which calls an Identity.UserManager to register a new account. It works fine if I call the Account controller directly w/ fiddler or another c# application. However, when I try to do it via Unit Testing. The service is called/reached, but when it try to insert the record it says: "Cannot Connect to Server - A network-related or instance-specific error"

public class AccountController : ApiController
{        
    public IHttpActionResult Post([FromBody]string value)
    {
        NewUserBase user = (NewUserBase)JsonConvert.DeserializeObject<NewUserBase>(value);
        IdentityUser u = new IdentityUser();
        u.UserName = user.UserName;
        u.PasswordHash = user.Password;
        return RegisterNonAsync(u);
    }
}

public class AuthRepository : IDisposable
{
    public IdentityResult RegisterUserNonAsync(IdentityUser IdentityUser)
    {
        try
        {
            //This line works when Account controller is called from fiddler, a c# application using webclient, but fails when being called from unit test
            result = _userManager.Create(IdentityUser, IdentityUser.PasswordHash);
            return result;
        }
        catch (DbEntityValidationException ex)
        {
            return null;
        }
    }
}


[TestClass]
public class TestAccountController
{
    [TestMethod]
    public void CreateUser_ShouldCreateANewUser()
    {
        string userNameToCreate = "TestUserForUnitTest";
        string password = "password123";

        var controller = new AccountController();
        controller.Post("{\"UserName\":\"" + userNameToCreate +"\", \"Password\":\"" + password  + "\"}");

        OAuthService.AuthRepository authRepo = new OAuthService.AuthRepository();
        var user = authRepo.FindUser(userNameToCreate, password);
    }
}

Aucun commentaire:

Enregistrer un commentaire