开发者

when unit testing an asp.net controller, where do you mock the httprequestbase?

开发者 https://www.devze.com 2022-12-14 18:11 出处:网络
when unit testing a asp.net controller, don\'t you have to somehow mock the httpcontextbase? All my controllers inherit from a custom controller class that I wrote (it just adds some common propertie

when unit testing a asp.net controller, don't you have to somehow mock the httpcontextbase?

All my controllers inherit from a custom controller class that I wrote (it just adds some common properties to the original controller class). So its like:

public class MyController : Controller
{
    protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext context)
    {
         // look for a specif开发者_运维技巧ic cookie
    }

}

so really want to start unit testing my controllers, just unsure how I go about mocking the controller classes and the httpcontext that goes with it.


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

var httpCtxStub = new Mock<HttpContextBase>();

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号