locked
Mocking HttpContext in a class library. RRS feed

  • Question

  • User-963208184 posted

    Hi all,

    I have a method in a class library project and I have the following line of code that attempts to build a redirect url based on the address that is currently being used.

                    _settingsModel.RedirectUrl = _settingsModel.RedirectUrl.Contains("~") ? _settingsModel.RedirectUrl.Replace("~", string.Format("https://{1}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Host)) : _settingsModel.RedirectUrl;
    

    I'm attempting to mock the method using moq. But of course I have not got an active context, so my moq fails because  HttpContext.Current is null.

    in my test projects test method I have:

    var mockPrepare = new Mock<Prepare>(_detailsModel,_dustomerDetailsModel,_settingsModel);
                
                var ret = mockPrepare.Object.Post();

    mockPrepare is initialised with the 3 objects correctly. When I debug it correctly steps into the Post method, then I get the error when I hit the line shown.

    Tuesday, May 12, 2015 11:00 AM

Answers

  • User-963208184 posted

    think I've found the answer:

                HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 12, 2015 11:07 AM