Web API - Issues with HttpContext.Current in owin for integration testing using moq The Next CEO of Stack OverflowMoq: unit testing a method relying on HttpContextHow to pass Owin context to a Repo being injected into Api controllerunity resolve instance at web api controllerMock HttpContext.Current in Test Init MethodWCF vs ASP.NET Web APIHow do I get ASP.NET Web API to return JSON instead of XML using Chrome?How to secure an ASP.NET Web APIWhat is the right way to self-host a Web API?Unit Testing Method with Moq where Collection = serivce.GetCollection()?Web API 2 OWIN Self Host can only connect via IP addressUnable to mock Owin context in C# WEB API REST service unit testOWIN Web API + OWIN Test Server + Ninject Dependency InjectionAccess OWIN Self-Hosted Web API Controller from Test

Domestic-to-international connection at Orlando (MCO)

Unclear about dynamic binding

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

0 rank tensor vs 1D vector

Is there a way to save my career from absolute disaster?

TikZ: How to reverse arrow direction without switching start/end point?

How to invert MapIndexed on a ragged structure? How to construct a tree from rules?

Is it convenient to ask the journal's editor for two additional days to complete a review?

Why isn't acceleration always zero whenever velocity is zero, such as the moment a ball bounces off a wall?

WOW air has ceased operation, can I get my tickets refunded?

Is it possible to replace duplicates of a character with one character using tr

Why do airplanes bank sharply to the right after air-to-air refueling?

Yu-Gi-Oh cards in Python 3

Poetry, calligrams and TikZ/PStricks challenge

Calculator final project in Python

Writing differences on a blackboard

The exact meaning of 'Mom made me a sandwich'

Bartok - Syncopation (1): Meaning of notes in between Grand Staff

Why the difference in type-inference over the as-pattern in two similar function definitions?

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Is French Guiana a (hard) EU border?

Axiom Schema vs Axiom

How to check if all elements of 1 list are in the *same quantity* and in any order, in the list2?

Does increasing your ability score affect your main stat?



Web API - Issues with HttpContext.Current in owin for integration testing using moq



The Next CEO of Stack OverflowMoq: unit testing a method relying on HttpContextHow to pass Owin context to a Repo being injected into Api controllerunity resolve instance at web api controllerMock HttpContext.Current in Test Init MethodWCF vs ASP.NET Web APIHow do I get ASP.NET Web API to return JSON instead of XML using Chrome?How to secure an ASP.NET Web APIWhat is the right way to self-host a Web API?Unit Testing Method with Moq where Collection = serivce.GetCollection()?Web API 2 OWIN Self Host can only connect via IP addressUnable to mock Owin context in C# WEB API REST service unit testOWIN Web API + OWIN Test Server + Ninject Dependency InjectionAccess OWIN Self-Hosted Web API Controller from Test










2















I am building a Web API application which will be hosted in an IIS environment. In order to perform end to end integration testing of my service(no mocking), I am using OWIN.



The problem is deep down in my service architecture, at the repository layer I am making use of HttpContext.Current to retrieve values from the header(say UserId). See this answer



If you look into the above code, I am making use GetUserInfo method throughout my application to fetch current user information. Another way to do is pass it as a parameter in all method(which I don't personally want to do).



I went through this great answer about including IOwinContext into the repository. I have tried it and it worked for self-hosting, but my end goal is to deploy the application on IIS.



My Questions:



  • Is there any way my code can handle both the use cases of OWIN self-hosting for integration testing & actual service deployment on IIS?

  • Is there any issue with my architecture? Something like I shouldn't be using OWIN at all, and use other tools like POSTMAN for testing.

I can post some code if it's required.



Edit:



As suggested by @Nkosi I might have to mock my HeaderService in order to perform integration testing with owin. I am not sure how can I mock one certain method using moq. Here is my code. Its strip down version in order to make as simple as possible.



Code:



public class CreditController : ApiController

private readonly ICreditService _creditService;

public CreditController(ICreditService creditService)

_creditService = creditService;


public IHttpActionResult CreditSummary([FromUri]string requestId)

var response = _creditService.GetCreditSummary(requestId);
return Ok(response);



public class CreditService : ICreditService

private readonly IHeaderService _headerService;
private readonly ICreditRepository _creditRepository;

public CreditService(ICreditRepository creditRepository, IHeaderService headerService)

_headerService = headerService;
_creditRepository = creditRepository;


public CreditObj GetCreditSummary(string req)

var userId = _headerService.GetHeaderFromHttpRequest();//Get User
var response = _creditRepository.GetDataFromDatabase(req, userId);
return response;



public interface IHeaderService

string GetHeaderFromHttpRequest();


public class HeaderService : IHeaderService

public string GetHeaderFromHttpRequest()

return HttpContext.Current.Request.Headers["USERID"];




Below is my code for integration testing: I am using OWIN for self-host. So i want to call the controller method but my GetHeaderFromHttpRequest method should return mock response.



[TestClass]
public class IntegrationTest

private static HttpClient _client;
private static IDisposable _webApp;

[ClassInitialize]
public static void Init(TestContext testContext)

_webApp = WebApp.Start<Startup>(url: Url);
_client = new HttpClient

BaseAddress = new Uri(Url)
;


[TestMethod]
public void TestDashboard()

var headerStub = new Mock<IHeaderService>();
headerStub.Setup(s => s.GetHeaderFromHttpRequest())
.Returns("MockUserId");

var builder = new UriBuilder(Url + "api/Credit/CreditSummary");

HttpResponseMessage responseMessage = _client.GetAsync(builder.ToString()).Result;
Assert.IsNotNull(responseMessage);



public class Startup

public void Configuration(IAppBuilder app)

var config = new HttpConfiguration();
WebApiConfig.Register(config); //This method having all routing/dependancy configuration
app.UseWebApi(config);




Problem:



  • When I debug this test case, how do I make sure that _headerService.GetHeaderFromHttpRequest() return mock response. As of now I dont know how can i inject my mocking service to actual controller method call.

Any advise?










share|improve this question
























  • You can still do end to end testing with a mock. If in this case you are not actually running on IIS, (which is what you would need in order for HttpContext.Current to work) Then you would still need to mock the abstracted service to avoid that static coupling.

    – Nkosi
    Mar 22 at 9:48











  • I am not sure if I understood you correctly. Are you saying that I should mock HttpContext.Current and/or HeaderService (service which uses HttpContext object) in my integration test? Not sure, if it's a good approach to mock anything when doing integration testing.

    – Shaggy
    Mar 22 at 16:37











  • Is the shown Startup the one used for the test? You can register a dependency resolver that is aware of the IHeaderService to return the mock when it is to be injected.

    – Nkosi
    Mar 23 at 1:14
















2















I am building a Web API application which will be hosted in an IIS environment. In order to perform end to end integration testing of my service(no mocking), I am using OWIN.



The problem is deep down in my service architecture, at the repository layer I am making use of HttpContext.Current to retrieve values from the header(say UserId). See this answer



If you look into the above code, I am making use GetUserInfo method throughout my application to fetch current user information. Another way to do is pass it as a parameter in all method(which I don't personally want to do).



I went through this great answer about including IOwinContext into the repository. I have tried it and it worked for self-hosting, but my end goal is to deploy the application on IIS.



My Questions:



  • Is there any way my code can handle both the use cases of OWIN self-hosting for integration testing & actual service deployment on IIS?

  • Is there any issue with my architecture? Something like I shouldn't be using OWIN at all, and use other tools like POSTMAN for testing.

I can post some code if it's required.



Edit:



As suggested by @Nkosi I might have to mock my HeaderService in order to perform integration testing with owin. I am not sure how can I mock one certain method using moq. Here is my code. Its strip down version in order to make as simple as possible.



Code:



public class CreditController : ApiController

private readonly ICreditService _creditService;

public CreditController(ICreditService creditService)

_creditService = creditService;


public IHttpActionResult CreditSummary([FromUri]string requestId)

var response = _creditService.GetCreditSummary(requestId);
return Ok(response);



public class CreditService : ICreditService

private readonly IHeaderService _headerService;
private readonly ICreditRepository _creditRepository;

public CreditService(ICreditRepository creditRepository, IHeaderService headerService)

_headerService = headerService;
_creditRepository = creditRepository;


public CreditObj GetCreditSummary(string req)

var userId = _headerService.GetHeaderFromHttpRequest();//Get User
var response = _creditRepository.GetDataFromDatabase(req, userId);
return response;



public interface IHeaderService

string GetHeaderFromHttpRequest();


public class HeaderService : IHeaderService

public string GetHeaderFromHttpRequest()

return HttpContext.Current.Request.Headers["USERID"];




Below is my code for integration testing: I am using OWIN for self-host. So i want to call the controller method but my GetHeaderFromHttpRequest method should return mock response.



[TestClass]
public class IntegrationTest

private static HttpClient _client;
private static IDisposable _webApp;

[ClassInitialize]
public static void Init(TestContext testContext)

_webApp = WebApp.Start<Startup>(url: Url);
_client = new HttpClient

BaseAddress = new Uri(Url)
;


[TestMethod]
public void TestDashboard()

var headerStub = new Mock<IHeaderService>();
headerStub.Setup(s => s.GetHeaderFromHttpRequest())
.Returns("MockUserId");

var builder = new UriBuilder(Url + "api/Credit/CreditSummary");

HttpResponseMessage responseMessage = _client.GetAsync(builder.ToString()).Result;
Assert.IsNotNull(responseMessage);



public class Startup

public void Configuration(IAppBuilder app)

var config = new HttpConfiguration();
WebApiConfig.Register(config); //This method having all routing/dependancy configuration
app.UseWebApi(config);




Problem:



  • When I debug this test case, how do I make sure that _headerService.GetHeaderFromHttpRequest() return mock response. As of now I dont know how can i inject my mocking service to actual controller method call.

Any advise?










share|improve this question
























  • You can still do end to end testing with a mock. If in this case you are not actually running on IIS, (which is what you would need in order for HttpContext.Current to work) Then you would still need to mock the abstracted service to avoid that static coupling.

    – Nkosi
    Mar 22 at 9:48











  • I am not sure if I understood you correctly. Are you saying that I should mock HttpContext.Current and/or HeaderService (service which uses HttpContext object) in my integration test? Not sure, if it's a good approach to mock anything when doing integration testing.

    – Shaggy
    Mar 22 at 16:37











  • Is the shown Startup the one used for the test? You can register a dependency resolver that is aware of the IHeaderService to return the mock when it is to be injected.

    – Nkosi
    Mar 23 at 1:14














2












2








2


1






I am building a Web API application which will be hosted in an IIS environment. In order to perform end to end integration testing of my service(no mocking), I am using OWIN.



The problem is deep down in my service architecture, at the repository layer I am making use of HttpContext.Current to retrieve values from the header(say UserId). See this answer



If you look into the above code, I am making use GetUserInfo method throughout my application to fetch current user information. Another way to do is pass it as a parameter in all method(which I don't personally want to do).



I went through this great answer about including IOwinContext into the repository. I have tried it and it worked for self-hosting, but my end goal is to deploy the application on IIS.



My Questions:



  • Is there any way my code can handle both the use cases of OWIN self-hosting for integration testing & actual service deployment on IIS?

  • Is there any issue with my architecture? Something like I shouldn't be using OWIN at all, and use other tools like POSTMAN for testing.

I can post some code if it's required.



Edit:



As suggested by @Nkosi I might have to mock my HeaderService in order to perform integration testing with owin. I am not sure how can I mock one certain method using moq. Here is my code. Its strip down version in order to make as simple as possible.



Code:



public class CreditController : ApiController

private readonly ICreditService _creditService;

public CreditController(ICreditService creditService)

_creditService = creditService;


public IHttpActionResult CreditSummary([FromUri]string requestId)

var response = _creditService.GetCreditSummary(requestId);
return Ok(response);



public class CreditService : ICreditService

private readonly IHeaderService _headerService;
private readonly ICreditRepository _creditRepository;

public CreditService(ICreditRepository creditRepository, IHeaderService headerService)

_headerService = headerService;
_creditRepository = creditRepository;


public CreditObj GetCreditSummary(string req)

var userId = _headerService.GetHeaderFromHttpRequest();//Get User
var response = _creditRepository.GetDataFromDatabase(req, userId);
return response;



public interface IHeaderService

string GetHeaderFromHttpRequest();


public class HeaderService : IHeaderService

public string GetHeaderFromHttpRequest()

return HttpContext.Current.Request.Headers["USERID"];




Below is my code for integration testing: I am using OWIN for self-host. So i want to call the controller method but my GetHeaderFromHttpRequest method should return mock response.



[TestClass]
public class IntegrationTest

private static HttpClient _client;
private static IDisposable _webApp;

[ClassInitialize]
public static void Init(TestContext testContext)

_webApp = WebApp.Start<Startup>(url: Url);
_client = new HttpClient

BaseAddress = new Uri(Url)
;


[TestMethod]
public void TestDashboard()

var headerStub = new Mock<IHeaderService>();
headerStub.Setup(s => s.GetHeaderFromHttpRequest())
.Returns("MockUserId");

var builder = new UriBuilder(Url + "api/Credit/CreditSummary");

HttpResponseMessage responseMessage = _client.GetAsync(builder.ToString()).Result;
Assert.IsNotNull(responseMessage);



public class Startup

public void Configuration(IAppBuilder app)

var config = new HttpConfiguration();
WebApiConfig.Register(config); //This method having all routing/dependancy configuration
app.UseWebApi(config);




Problem:



  • When I debug this test case, how do I make sure that _headerService.GetHeaderFromHttpRequest() return mock response. As of now I dont know how can i inject my mocking service to actual controller method call.

Any advise?










share|improve this question
















I am building a Web API application which will be hosted in an IIS environment. In order to perform end to end integration testing of my service(no mocking), I am using OWIN.



The problem is deep down in my service architecture, at the repository layer I am making use of HttpContext.Current to retrieve values from the header(say UserId). See this answer



If you look into the above code, I am making use GetUserInfo method throughout my application to fetch current user information. Another way to do is pass it as a parameter in all method(which I don't personally want to do).



I went through this great answer about including IOwinContext into the repository. I have tried it and it worked for self-hosting, but my end goal is to deploy the application on IIS.



My Questions:



  • Is there any way my code can handle both the use cases of OWIN self-hosting for integration testing & actual service deployment on IIS?

  • Is there any issue with my architecture? Something like I shouldn't be using OWIN at all, and use other tools like POSTMAN for testing.

I can post some code if it's required.



Edit:



As suggested by @Nkosi I might have to mock my HeaderService in order to perform integration testing with owin. I am not sure how can I mock one certain method using moq. Here is my code. Its strip down version in order to make as simple as possible.



Code:



public class CreditController : ApiController

private readonly ICreditService _creditService;

public CreditController(ICreditService creditService)

_creditService = creditService;


public IHttpActionResult CreditSummary([FromUri]string requestId)

var response = _creditService.GetCreditSummary(requestId);
return Ok(response);



public class CreditService : ICreditService

private readonly IHeaderService _headerService;
private readonly ICreditRepository _creditRepository;

public CreditService(ICreditRepository creditRepository, IHeaderService headerService)

_headerService = headerService;
_creditRepository = creditRepository;


public CreditObj GetCreditSummary(string req)

var userId = _headerService.GetHeaderFromHttpRequest();//Get User
var response = _creditRepository.GetDataFromDatabase(req, userId);
return response;



public interface IHeaderService

string GetHeaderFromHttpRequest();


public class HeaderService : IHeaderService

public string GetHeaderFromHttpRequest()

return HttpContext.Current.Request.Headers["USERID"];




Below is my code for integration testing: I am using OWIN for self-host. So i want to call the controller method but my GetHeaderFromHttpRequest method should return mock response.



[TestClass]
public class IntegrationTest

private static HttpClient _client;
private static IDisposable _webApp;

[ClassInitialize]
public static void Init(TestContext testContext)

_webApp = WebApp.Start<Startup>(url: Url);
_client = new HttpClient

BaseAddress = new Uri(Url)
;


[TestMethod]
public void TestDashboard()

var headerStub = new Mock<IHeaderService>();
headerStub.Setup(s => s.GetHeaderFromHttpRequest())
.Returns("MockUserId");

var builder = new UriBuilder(Url + "api/Credit/CreditSummary");

HttpResponseMessage responseMessage = _client.GetAsync(builder.ToString()).Result;
Assert.IsNotNull(responseMessage);



public class Startup

public void Configuration(IAppBuilder app)

var config = new HttpConfiguration();
WebApiConfig.Register(config); //This method having all routing/dependancy configuration
app.UseWebApi(config);




Problem:



  • When I debug this test case, how do I make sure that _headerService.GetHeaderFromHttpRequest() return mock response. As of now I dont know how can i inject my mocking service to actual controller method call.

Any advise?







c# asp.net-web-api owin moq httpcontext






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 21:15







Shaggy

















asked Mar 21 at 17:57









ShaggyShaggy

1,4841673121




1,4841673121












  • You can still do end to end testing with a mock. If in this case you are not actually running on IIS, (which is what you would need in order for HttpContext.Current to work) Then you would still need to mock the abstracted service to avoid that static coupling.

    – Nkosi
    Mar 22 at 9:48











  • I am not sure if I understood you correctly. Are you saying that I should mock HttpContext.Current and/or HeaderService (service which uses HttpContext object) in my integration test? Not sure, if it's a good approach to mock anything when doing integration testing.

    – Shaggy
    Mar 22 at 16:37











  • Is the shown Startup the one used for the test? You can register a dependency resolver that is aware of the IHeaderService to return the mock when it is to be injected.

    – Nkosi
    Mar 23 at 1:14


















  • You can still do end to end testing with a mock. If in this case you are not actually running on IIS, (which is what you would need in order for HttpContext.Current to work) Then you would still need to mock the abstracted service to avoid that static coupling.

    – Nkosi
    Mar 22 at 9:48











  • I am not sure if I understood you correctly. Are you saying that I should mock HttpContext.Current and/or HeaderService (service which uses HttpContext object) in my integration test? Not sure, if it's a good approach to mock anything when doing integration testing.

    – Shaggy
    Mar 22 at 16:37











  • Is the shown Startup the one used for the test? You can register a dependency resolver that is aware of the IHeaderService to return the mock when it is to be injected.

    – Nkosi
    Mar 23 at 1:14

















You can still do end to end testing with a mock. If in this case you are not actually running on IIS, (which is what you would need in order for HttpContext.Current to work) Then you would still need to mock the abstracted service to avoid that static coupling.

– Nkosi
Mar 22 at 9:48





You can still do end to end testing with a mock. If in this case you are not actually running on IIS, (which is what you would need in order for HttpContext.Current to work) Then you would still need to mock the abstracted service to avoid that static coupling.

– Nkosi
Mar 22 at 9:48













I am not sure if I understood you correctly. Are you saying that I should mock HttpContext.Current and/or HeaderService (service which uses HttpContext object) in my integration test? Not sure, if it's a good approach to mock anything when doing integration testing.

– Shaggy
Mar 22 at 16:37





I am not sure if I understood you correctly. Are you saying that I should mock HttpContext.Current and/or HeaderService (service which uses HttpContext object) in my integration test? Not sure, if it's a good approach to mock anything when doing integration testing.

– Shaggy
Mar 22 at 16:37













Is the shown Startup the one used for the test? You can register a dependency resolver that is aware of the IHeaderService to return the mock when it is to be injected.

– Nkosi
Mar 23 at 1:14






Is the shown Startup the one used for the test? You can register a dependency resolver that is aware of the IHeaderService to return the mock when it is to be injected.

– Nkosi
Mar 23 at 1:14













2 Answers
2






active

oldest

votes


















1














Based on @Nkosi's suggestion I was able to mock HeaderService for my integration testing.



Here is the code:



var container = new UnityContainer();

var mock = new Mock<IHeaderService>();
mock.Setup(x => x.GetHeaderFromHttpRequest()).Returns("MockId");
container.RegisterInstance(mock.Object);





share|improve this answer






























    0














    I followed this topic and use HttpContextBase in my old project.



    Moq: unit testing a method relying on HttpContext



    HttpContextWrapper is a wrapper for the HttpContext class, can construct an HttpContextWrapper like this:



    var wrapper = new HttpContextWrapper(HttpContext.Current);


    You can mock an HttpContextBase and set up your expectations on it using Moq



    var mockContext = new Mock<HttpContextBase>();





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55286550%2fweb-api-issues-with-httpcontext-current-in-owin-for-integration-testing-using%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Based on @Nkosi's suggestion I was able to mock HeaderService for my integration testing.



      Here is the code:



      var container = new UnityContainer();

      var mock = new Mock<IHeaderService>();
      mock.Setup(x => x.GetHeaderFromHttpRequest()).Returns("MockId");
      container.RegisterInstance(mock.Object);





      share|improve this answer



























        1














        Based on @Nkosi's suggestion I was able to mock HeaderService for my integration testing.



        Here is the code:



        var container = new UnityContainer();

        var mock = new Mock<IHeaderService>();
        mock.Setup(x => x.GetHeaderFromHttpRequest()).Returns("MockId");
        container.RegisterInstance(mock.Object);





        share|improve this answer

























          1












          1








          1







          Based on @Nkosi's suggestion I was able to mock HeaderService for my integration testing.



          Here is the code:



          var container = new UnityContainer();

          var mock = new Mock<IHeaderService>();
          mock.Setup(x => x.GetHeaderFromHttpRequest()).Returns("MockId");
          container.RegisterInstance(mock.Object);





          share|improve this answer













          Based on @Nkosi's suggestion I was able to mock HeaderService for my integration testing.



          Here is the code:



          var container = new UnityContainer();

          var mock = new Mock<IHeaderService>();
          mock.Setup(x => x.GetHeaderFromHttpRequest()).Returns("MockId");
          container.RegisterInstance(mock.Object);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 23 at 22:15









          ShaggyShaggy

          1,4841673121




          1,4841673121























              0














              I followed this topic and use HttpContextBase in my old project.



              Moq: unit testing a method relying on HttpContext



              HttpContextWrapper is a wrapper for the HttpContext class, can construct an HttpContextWrapper like this:



              var wrapper = new HttpContextWrapper(HttpContext.Current);


              You can mock an HttpContextBase and set up your expectations on it using Moq



              var mockContext = new Mock<HttpContextBase>();





              share|improve this answer



























                0














                I followed this topic and use HttpContextBase in my old project.



                Moq: unit testing a method relying on HttpContext



                HttpContextWrapper is a wrapper for the HttpContext class, can construct an HttpContextWrapper like this:



                var wrapper = new HttpContextWrapper(HttpContext.Current);


                You can mock an HttpContextBase and set up your expectations on it using Moq



                var mockContext = new Mock<HttpContextBase>();





                share|improve this answer

























                  0












                  0








                  0







                  I followed this topic and use HttpContextBase in my old project.



                  Moq: unit testing a method relying on HttpContext



                  HttpContextWrapper is a wrapper for the HttpContext class, can construct an HttpContextWrapper like this:



                  var wrapper = new HttpContextWrapper(HttpContext.Current);


                  You can mock an HttpContextBase and set up your expectations on it using Moq



                  var mockContext = new Mock<HttpContextBase>();





                  share|improve this answer













                  I followed this topic and use HttpContextBase in my old project.



                  Moq: unit testing a method relying on HttpContext



                  HttpContextWrapper is a wrapper for the HttpContext class, can construct an HttpContextWrapper like this:



                  var wrapper = new HttpContextWrapper(HttpContext.Current);


                  You can mock an HttpContextBase and set up your expectations on it using Moq



                  var mockContext = new Mock<HttpContextBase>();






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 23 at 1:27









                  Hien NguyenHien Nguyen

                  1,4831715




                  1,4831715



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55286550%2fweb-api-issues-with-httpcontext-current-in-owin-for-integration-testing-using%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript