[英]Unit Testing .net Web Api. Setting Query String values
The first line of my ApiController HttpGet action is this 我的ApiController HttpGet动作的第一行就是这个
var returnOnlyDefault = (Request.GetQueryNameValuePairs()
.Any(kv => ((kv.Key.ToLower() == "defaultview") && (kv.Value.ToLower() == "true"))));
This looks for a query string value of "defaultview". 这将查找“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. 请求uri当然是null。 The test is failing as it doesn't pick up the query string value.
测试失败,因为它没有获取查询字符串值。
You should set the request Uri: 您应该设置请求Uri:
controller.Request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:51083/?param1=someValue¶m2=anotherValue");
Now the get querystring params in your ApiController works as expected: 现在,ApiController中的get querystring params按预期工作:
var queryStringParams = Request.GetQueryNameValuePairs().ToList();
var param1 = queryStringParams.FirstOrDefault(kv => kv.Key.Equals("param1")).Value;
param1 is now 'someValue' and the unit test runs. param1现在是'someValue'并且单元测试运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.