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?
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");
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With