如何在单元测试中为 HttpRequest 模拟 UserAgent 属性?

How to mock the UserAgent property for an HttpRequest in a unit test?

我正在尝试为我的单元测试创​​建一个伪造的 HttpContext 并且还想设置 UserAgent 属性.

我尝试了下面的代码,但失败了,提示平台不受支持。

var httpRequest = new HttpRequest(null, "http:xyz.com", null);
httpRequest.Headers["UserAgent"] = "unitTest";

var stringWriter = new StringWriter();
var httpResponce = new HttpResponse(stringWriter);
HttpContext context = new HttpContext(httpRequest, httpResponce);

有什么帮助吗?

正如您在参考资料中看到的那样,UserAgent is extracted form the HttpWorkerRequest. The only way to change it, is by calling this constructor of HttpRequest 使用反射来传递 worker 请求:

internal HttpRequest(HttpWorkerRequest wr, HttpContext context)

随着我进一步调查,它似乎从远处 IIS class 检索属性,或者在使用 ISAPI 时使用 Server variable ALL_RAW.

我开始认为这可能会成为被嘲笑的可怕事情。您可能更幸运地自己覆盖 abstract class HttpWorkerRequest,但实施起来可能会成为一场噩梦。