How to Construct IdentityResult With Success == true

jakejgordon picture jakejgordon · Oct 9, 2014 · Viewed 17.2k times · Source

I have a class with Microsoft.AspNet.Identity.UserManager injected, and I want to expect the userManager.CreateAsync(user, password) method to return a Task where the IdentityResult.Succeeded = true. However, the only available constructors for IdentityResult are failure constructors that will cause Succeeded property to be false.

How does one create an IdentityResult that has Succeeded == true? IdentityResult doesn't implement an interface and Succeeded isn't virtual so I don't see any obvious ways of creating a mock object through Rhino Mocks (which i'm using as my mocking framework).

My method does something like the below. Providing this example to show why I might want to mock this.

  public async Task<IdentityResult> RegisterUser(NewUser newUser)
    {
        ApplicationUser newApplicationUser = new ApplicationUser()
        {
            UserName = newUser.UserName,
            Email = newUser.Email
        };

        IdentityResult identityResult = await applicationUserManager.CreateAsync(newApplicationUser, newUser.Password);

        if(identityResult.Succeeded)
        {
            someOtherDependency.DoSomethingAmazing();
        }

        return identityResult;
    }

I'm trying to write a unit test that ensures that someOtherDependency.DoSomethingAmazing() is called if identityResult.Succeeded is true. Thanks for any help!

Answer

jt000 picture jt000 · Oct 9, 2014

Would the static IdentityResult.Success property work? http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityresult.success(v=vs.108).aspx

Edit: To add some more detail, it seems what you want to do is get your mocked CreateAsync to return an IdentityResult where Suceeded is true. For that I would just return IdentityResult.Success from your mock. There's shouldn't be a need to mock the IdentityResult itself.

Example: How to setup a service that returns Successful identity result.

    applicationUserManagerMock.Setup(s => 
        s.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>())
    ).ReturnsAsync(IdentityResult.Success);