Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test Url.Link in .net core

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.

like image 300
Carl Thomas Avatar asked Oct 25 '25 04:10

Carl Thomas


2 Answers

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

like image 180
Carl Thomas Avatar answered Oct 26 '25 18:10

Carl Thomas


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
//...
like image 25
Nkosi Avatar answered Oct 26 '25 17:10

Nkosi