1

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);
    }
}
Samuel Elrod
  • 337
  • 1
  • 3
  • 13
  • 1
    Did you try to run your Visual Studio as an admin and then test the code? – Yuri Apr 27 '15 at 17:52
  • Just tried. Same issue. When I step through the code for the IdentityDbContext, it times out tying to establish db connection – Samuel Elrod Apr 27 '15 at 17:57
  • You need to mock the request. Please see this article http://stackoverflow.com/questions/1106398/how-to-unit-test-an-mvc-controller-action-which-depends-on-authentification-in-c – Yuri Apr 28 '15 at 19:02
  • God bless you, can you write that as an answer @Yuri so I can mark it as an answer. – Samuel Elrod Apr 29 '15 at 19:28

1 Answers1

1

In case to make it work you will need to mock your request.

var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.IsAuthenticated).Returns(true) 

Please see this article from another stackoverflow user

Community
  • 1
  • 1
Yuri
  • 2,820
  • 4
  • 28
  • 40