3
votes

I am using .net core creating an API. One of my methods is a POST which inserts a new record. The successful response returns a 201 Created. In .net I can use the helper CreatedResult e.g.

return Created(new Uri(Url.Link("get_method", new { id = record.id })), record);

This will return a 201 response with the correct Location header set. The Location header uses the incoming request to build up the url using the hostname.

When unit testing in .net webapi2 I could create a custom HttpRequestMessage and set the hostname myself. Now this seems to have disappeared in the new .net core framework.

How do I mock the incoming request so I can unit test and create a valid Location header.

I believe that I need to be mocking HttpRequest on the HttpContext for the controller.

UserController controller = new UserController();
controller.ControllerContext.HttpContext.Request = ?

How to I mock this Request parameter? It is a readonly property.

3

3 Answers

7
votes

Following on from @Nkosi I found that I needed to mock the IUrlHelper

Mock<IUrlHelper> urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.Link(It.IsAny<string>(), It.IsAny<object>())).Returns("http://localhost");

UserController controller = new UserController();
controller.Url = urlHelper.Object

Now when Url.Link is called inside the controller it returns my https://localhost

0
votes
controller.ControllerContext.HttpContext.Request["parameter_name"]
0
votes

Checking some of the unit tests for asp.net core on Github, came across one that should suit your needs. Their test used Moq

// Arrange
var controller = new UserController();

var request = Mock.Of<HttpRequest>();
var httpContext = new Mock<HttpContext>();
httpContext
    .Setup(c => c.Request)
    .Returns(request);

controller.ControllerContext.HttpContext = httpContext.Object;

// Act
//...