-4

Could you please help me with writing UnitTest for this method? I tried a couple of ways but I could not solve it.

public ActionResult ChangePass()
{
    if (Request.IsAuthenticated)
    {
        return View();
    }
    else
    {
        return RedirectToAction("Index", "Index", new { area = "" });
    }
}

Here is what I am trying to do.

[TestMethod]
    public void ChangePass()
    {

        var identity = new GenericIdentity("admin@gmail.com");
        var controller = new ProfilePageController();
        var controllerContext = new Mock<ControllerContext>();
        var principal = new Mock<IPrincipal>();
       principal.Setup(p => p.IsInRole("user")).Returns(true);
        principal.SetupGet(x => x.Identity.Name).Returns("admin@gmail.com");
        controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
        controller.ControllerContext = controllerContext.Object;
        NUnit.Framework.Assert.AreEqual(controller.ChangePass(), identity.Name);
        }

1 Answers1

2

First of all it's a controller action method which shouldn't be unit tested at all. Rather only the business logic should be tested. Why?

cause, look at the line Request.IsAuthenticated. at time when you are unit testing there is no Request object present and thus that line is bound to throw NullRefException.

Moreover your posted action method ChangePass() has no business logic involved which to be tested at all

Rahul
  • 76,197
  • 13
  • 71
  • 125