1

My controller using following line to assign url to the session

this.Session["MyUrl"] = Request.Url.ToString(); 

on unit test project side I setup controller like this

var fakeHttpContext = new Mock<HttpContextBase>(); var controllerContext = new Mock<ControllerContext>(); controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object); this.controller.ControllerContext = controllerContext.Object; controllerContext.SetupGet(x => x.HttpContext.Request.Url).Returns(new Uri("/Home/Details", UriKind.Relative)); 

on this last line I'm trying to setup Request.Url in order to pass the value I expect on the controller side.

All I'm getting as a result on Request.Url is '/Home/Details'.

Do I need to mock whole Url object inside request in order to get this to work?

Update: I setup session object in httpcontext setup

fakeHttpContext.Setup(x => x.Session["MyUrl"]).Returns("/Home/Details"); 

but still experiencing the same issue.

10
  • You specified /Home/Details in your mock. What value do you expect to get in the controller? Commented Jan 27, 2017 at 8:10
  • I expect /Home/Details on the controller side also. Commented Jan 27, 2017 at 8:17
  • Isn't what you are getting? Commented Jan 27, 2017 at 8:18
  • yes, that's exactly what I'm getting but still I'm getting Additional information: Object reference not set to an instance of an object e exception. My guess is that Request.Url.OriginalString is populated and all other Request.Url fields return exceptions. Commented Jan 27, 2017 at 8:24
  • Try providing an absolute url in your mock: new Uri("http://example.com/Home/Details"). Commented Jan 27, 2017 at 8:25

1 Answer 1

4

You don't seem to be properly mocking the ControllerContext. Try this:

// arrange var controller = new HomeController(); var context = new Mock<HttpContextBase>(); var session = new Mock<HttpSessionStateBase>(); context.Setup(x => x.Request.Url).Returns(new Uri("/Home/Details", UriKind.Relative)); context.Setup(x => x.Session).Returns(session.Object); var requestContext = new RequestContext(context.Object, new RouteData()); controller.ControllerContext = new ControllerContext(requestContext, controller); // act var actual = controller.Index(); // assert session.VerifySet(x => x["MyUrl"] = "/Home/Details"); ... 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.