ASP.NET MVC unit test controller with HttpContext

前端 未结 5 1321
攒了一身酷
攒了一身酷 2020-11-28 07:21

I am trying to write a unit test for my one controller to verify if a view was returned properly, but this controller has a basecontroller that accesses the HttpContext.Curr

5条回答
  •  一生所求
    2020-11-28 07:50

    Unless you use Typemock or Moles, you can't.

    In ASP.NET MVC you are not supposed to be using HttpContext.Current. Change your base class to use ControllerBase.ControllerContext - it has a HttpContext property that exposes the testable HttpContextBase class.

    Here's an example of how you can use Moq to set up a Mock HttpContextBase:

    var httpCtxStub = new Mock();
    
    var controllerCtx = new ControllerContext();
    controllerCtx.HttpContext = httpCtxStub.Object;
    
    sut.ControllerContext = controllerCtx;
    
    // Exercise and verify the sut
    

    where sut represents the System Under Test (SUT), i.e. the Controller you wish to test.

提交回复
热议问题