Skip to content

Commit

Permalink
Update moq.md
Browse files Browse the repository at this point in the history
  • Loading branch information
sj-net authored Sep 27, 2024
1 parent 58e01d3 commit d606b06
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion docs/testing/moq.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,27 @@ grand_parent: My Docs
### How to MOQ a HTTPContext in MVC/API for .Net Framework
---

- We need to set the Controller Context for the controller under test. From that the HTTPContext is pulled.

```csharp
public static ControllerContext GetControllerContext(Controller controller)
{
var mockHttpContext = new Mock<HttpContextBase>();
var mockRequest = new Mock<HttpRequestBase>();

var routeData = new RouteData();
routeData.Values["controller"] = "Some controller name";
routeData.Values["action"] = "some action name";
// feel free to set anything else required for the context like route data or claims etc.
var requestContext = new RequestContext(mockHttpContext.Object, routeData);
mockHttpContext.Setup(ctx => ctx.Request).Returns(mockRequest.Object);
mockHttpContext.Setup(ctx => ctx.Request.RequestContext).Returns(requestContext);
return new ControllerContext(requestContext, controller) { HttpContext = mockHttpContext.Object };
}

// usage inside a test
```
var _sut = new MyController(); // inject dependencies if any
_sut.ControllerContext = GetControllerContext( _sut);
```

0 comments on commit d606b06

Please sign in to comment.