3

I am writing unit Test cases for my Home Controller, in Home controller i have Action Method called MyProfile which calls ChangePasswordAsync Method in UserManager class. How to test application User manager

Below is my Controller code

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> MyProfile(ChangePasswordViewModel model)
{
  if (!ModelState.IsValid)
     {
       return View(model);
     }
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
    if (result.Succeeded)
       {
     var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
      if (user != null)
        {
      await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
       }
      var verification_uid = Guid.NewGuid().ToString();


        }
Charan Tej
  • 61
  • 5

2 Answers2

5

You don't. This is a prime example of testing the framework, which you shouldn't be doing. You need to write tests for your application code, not for Identity or any other part of ASP.NET. That code is already well-tested by Microsoft. You can safely assume that calling ChangePasswordAsync will in fact change the user's password. Otherwise, the Identity release you're running would have failed its testrun and never been released.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • file-->new project in mvc 5 generates test code for testing your controllers.... How do you advise testing change password ActionResult? –  Mar 10 '17 at 21:30
  • Mock a user with one password, run the action with a different password. Assert password on user is new password and not old password.. Pretty standard test setup. – Chris Pratt Mar 10 '17 at 21:45
0

I am able to test my controller code in a test. It is simple and does the job but keep in mind that the controller code is application tier and is more or less a black box to my test... meaning ChangePasswordAsync is working as expected - under the covers. I am also having to write my own test code to get a list of users by role in my test to add a claim so I am still learning. Hope this helps!

<TestMethod()> Public Sub Index()

        ' Arrange
        Dim controller As New HomeController()

        ' Act
        Dim result As ViewResult = DirectCast(controller.Index(), ViewResult)

        ' **Assert that your change password returns the expected model**
        Assert.IsNotNull(result)
    End Sub