1

I am using Moq framework to mock objects in my project. I want to save the user profile which is calling UserManager.SetPhoneNUmberAsync of AspNet.Identity. Here is my code:

 public async Task<ActionResult> SaveProfile(DistributorViewModel distributorModel)
    {
        if (ModelState.IsValid)
        {
            string currentUserId = User.Identity.GetUserId();
            distributorModel.UserDetailViewModel.ModifiedDate = System.DateTime.Now;
            distributorModel.UserDetailViewModel.ModifiedBy =Guid.Parse( currentUserId);
            var isUpdated = this.distributorService.Update(distributorModel.UserDetailViewModel);

            IdentityResult result = await UserManager.SetPhoneNumberAsync(currentUserId, distributorModel.UserDetailViewModel.MobileNo);

            if (result.Succeeded && isUpdated)
            {
                Flash.Success(Messages.ProfileUpdatedSuccessfully);
            }
            else
            {
                Flash.Error(Messages.ProfileUpdationError);
            }
        }
        return RedirectToAction("Index", distributorModel);
    }

Its throwing error on UserManager.SetPhoneNumberAsync. How can I mock this method?

tereško
  • 58,060
  • 25
  • 98
  • 150
Rashi
  • 23
  • 5

2 Answers2

2

Something similar to this should work:

        var manager = new Mock<UserManager<ApplicationUser>();
        manager.Setup(m => m.SetPhoneNumberAsync(userId, "phoneNumber").ReturnsAsync(IdentityResult.Succeeded()).Verifiable();
Hao Kung
  • 28,040
  • 6
  • 84
  • 93
  • Thanks for the reply. It worked for me like this: userManager.Setup(m => m.SetPhoneNumberAsync(It.IsAny(),"")).ReturnsAsync(IdentityResult.Success).Verifiable(); – Rashi Jul 19 '14 at 05:42
0

You can also create class IdentityResultMock which inherited from IdentityResult. Than you can assign Successed property from IdentityResultMock because IdentityResult has protected constructor.

Please refer to my answer here.

Community
  • 1
  • 1
kat1330
  • 5,134
  • 7
  • 38
  • 61