Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the query string for a request within a unit test in ASP.NET Core?

Tags:

asp.net-core

I am writing unit tests for my ASP.NET Core site, and I need to be able to set the query string for the request. How can I set the query string for a request within a unit test in ASP.NET Core?

like image 298
Adrian Toman Avatar asked Feb 02 '18 02:02

Adrian Toman


2 Answers

You first must first build the object tree of Controller -> ControllerContext -> DefaultHttpContext. The request property for a DefaultHttpContext object has the type DefaultHttpRequest. So, if you cast HttpContext.Request to DefaultHttpRequest you are able to set the QueryString parameter.

var controller = new FunController()
{
    ControllerContext = new ControllerContext
    {
        HttpContext = new DefaultHttpContext()
    }
};
controller.HttpContext.Request as DefaultHttpRequest).QueryString = new QueryString("?funfactor=100");
like image 130
Adrian Toman Avatar answered Sep 26 '22 02:09

Adrian Toman


In case you are OK to use Integration testing you could also use TestServer approach. See the details here - Testing controller logic in ASP.NET Core. In this case the test for controller action with query parameters might look like this:

var hostBuilder = new WebHostBuilder()
    .UseEnvironment("Testing")
    .UseStartup<Startup>();

var server = new TestServer(hostBuilder);
var client = server.CreateClient();

HttpResponseMessage response = client.GetAsync("/api/mycontroller/things?param=value").Result;
like image 27
Dmitry Pavlov Avatar answered Sep 26 '22 02:09

Dmitry Pavlov