0

I have this function and unit test.

ProfileController Code

[HttpPost]
public ActionResult Edit(int? id)
{
  var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile", new { id = 0 });
  return Json(new { Url = redirectUrl });
}

unit test code

[TestMethod]
public void TestDetailsViewData()
{
    var controller = new ProfileController(_Profile); 

    var result = controller.Edit(1) as ViewResult;
    var profile = (VIEWMODELS.Customer.Profile)result.ViewData.Model;
    Assert.AreEqual("Testor", profile.cardName);
}

i would like to test this function and this function will redirect to index page and return ViewPage with data. But the problem is when i run this unit test code i got Null exception at this line ,because of the Request is NULL

var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile", new { id = 0 });

so may i know how could i test this?

Updated with Moq function After further reading and get some sample code from here it seem request able to filled with value but now the RequestContext is NULL, anyone can point me to right place for me to study?

[TestMethod]
        public void TestDetailsViewData()
        {
            var request = new Mock<HttpRequestBase>(); 
            request.SetupGet(x => x.Headers).Returns(
                new System.Net.WebHeaderCollection {
                {"X-Requested-With", "XMLHttpRequest"}
            });

            var context = new Mock<HttpContextBase>();
            context.SetupGet(x => x.Request).Returns(request.Object);
            //context.SetupGet(x => x.Request.RequestContext ).Returns(request.Object.RequestContext);

            var controller = new ProfileController(_Profile);
            controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
            controller.Request.RequestContext = context.Object.Request.RequestContext;
            var result = controller.Edit(1) as ViewResult;
            var profile = (VIEWMODELS.Customer.Profile)result.ViewData.Model;
            Assert.AreEqual("testor", profile.cardName);
        }
Community
  • 1
  • 1
tsohtan
  • 830
  • 1
  • 13
  • 33

1 Answers1

0

The error is occurring because the request is not defined in Test method.I think you have to use visual studio fakes.

https://msdn.microsoft.com/en-us/library/hh549175.aspx

Spider man
  • 3,224
  • 4
  • 30
  • 42