1

I am writing a unit test where I need to set the URL of the incoming request in order evaluate the URL inside the controller's method. I am using FakeItEasy and NUnit3.

Here is the code under test and the relevant part:

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel loginViewModel)
{
...
   var queryString = Uri.UnescapeDataString(Request.Query["returnUrl"]);
...
}

I want to set queryString to a value I specify in my unit test. Can someone help me with example code? The system under test is the controller. I can only seem to find Moq related code. Seems simple enough.

mgtb
  • 27
  • 7
  • I suppose you could set the required value of the Request Query through an HttpContext. [This](https://stackoverflow.com/questions/41400030/mock-httpcontext-for-unit-testing-a-net-core-mvc-controller) question & answer might be just what you were looking for. – Emil Terman May 09 '20 at 16:08

2 Answers2

0

You could just bind a parameter to the query string like this:

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel loginViewModel, [FromQuery] string returnUrl)
{
}

And in your test, call the Login method with the value you want for returnUrl

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
-2

No need to user FakeItEasy or NUnit to solve this. Here is the line of code that solved my issue:

_accountController.Request.QueryString = new QueryString("?returnUrl=value");

Replaced 'param=value' with what was needed to test it.

mgtb
  • 27
  • 7