Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以使用dynamic重定向HttpContext.Current.Request吗?_C#_Dynamic_Rhino Mocks - Fatal编程技术网

C# 我可以使用dynamic重定向HttpContext.Current.Request吗?

C# 我可以使用dynamic重定向HttpContext.Current.Request吗?,c#,dynamic,rhino-mocks,C#,Dynamic,Rhino Mocks,我正在使用Rhinomock进行测试。它不擅长重定向静态;我曾考虑过使用另一个库,比如Moles的继承者(编辑:我想Fakes工具只在VS2012中可用?这很糟糕)或TypeMock,但我不想这样做 我有一个接受HttpRequest对象的第三方库。我的第一次尝试是使用: public void GetSamlResponseFromHttpPost(out XmlElement samlResponse, out string relayState, HttpContextBase ht

我正在使用Rhinomock进行测试。它不擅长重定向静态;我曾考虑过使用另一个库,比如Moles的继承者(编辑:我想Fakes工具只在VS2012中可用?这很糟糕)或TypeMock,但我不想这样做

我有一个接受HttpRequest对象的第三方库。我的第一次尝试是使用:

public void GetSamlResponseFromHttpPost(out XmlElement samlResponse, 
  out string relayState, HttpContextBase httpContext = null)
 {
  var wrapper = httpContext ?? new HttpContextWrapper(HttpContext.Current); 
  // signature of the next line cannot be changed
  ServiceProvider.ReceiveSAMLResponseByHTTPPost(
      wrapper.ApplicationInstance.Context.Request, out samlResponse, out relayState);
一切看起来都很好,直到我去测试它。这里真正的问题是我需要去掉
包装器.ApplicationInstance.Context.Request
。这导致了一大堆旧式的“ASP.NET不喜欢测试”的痛苦


我听说您可以使用C#中的
动态
魔术来重定向静态方法。但是,找不到任何使用HttpContext这样的东西来实现这一点的例子。这可能吗

这不是一个理想的解决方案,但我测试这一点的解决方案是使用反射并修改引擎盖下的对象:

httpRequest = new HttpRequest("default.aspx", "http://test.com", null);
var collection = httpRequest.Form;

// inject a value into the Form directly
var propInfo = collection.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
propInfo.SetValue(collection, false, new object[] { });
collection["theFormField"] = val;
propInfo.SetValue(collection, true, new object[] { });

var appInstance = new HttpApplication();
var w = new StringWriter();
httpResponse = new HttpResponse(w);
httpContext = new HttpContext(httpRequest, httpResponse);

// set the http context on the app instance to a new value
var contextField = appInstance.GetType().GetField("_context", BindingFlags.Instance | BindingFlags.NonPublic);
contextField.SetValue(appInstance, httpContext);

Context.Stub(ctx => ctx.ApplicationInstance).Return(appInstance);

我的目标是让
wrapper.ApplicationInstance.Context.Request在被请求时返回表单字段值。它可能是迂回的,但它是有效的。这段代码只存在于测试代码中,所以我很满意

看看MvcContrib测试助手。您可以在nuget上找到它。@gdoron我怀疑该项目中的基类是MVC风格的(HttpContextBase等)。。。。很抱歉但也许你可以调整一下。