4

The first line of my ApiController HttpGet action is this

var returnOnlyDefault = (Request.GetQueryNameValuePairs()
    .Any(kv => ((kv.Key.ToLower() == "defaultview") && (kv.Value.ToLower() == "true"))));

This looks for a query string value of "defaultview". The code 'works', but i'm having trouble unit testing it.

In my unit test i am doing the following

var controller = new Controllers.ViewsController { Request = new HttpRequestMessage() };
controller.Request.Properties.Add(new KeyValuePair<string, object>("defaultview", "true"));

the request uri is null of course. The test is failing as it doesn't pick up the query string value.

1 Answer 1

15

You should set the request Uri:

controller.Request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:51083/?param1=someValue&param2=anotherValue");

Now the get querystring params in your ApiController works as expected:

var queryStringParams = Request.GetQueryNameValuePairs().ToList();
var param1 = queryStringParams.FirstOrDefault(kv => kv.Key.Equals("param1")).Value;

param1 is now 'someValue' and the unit test runs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.