我正在使用 HttpResponseBase 对象测试 AspNet MVC 应用程序中的 HttpModule,正如 Kazi Rashid's blog 所建议的那样
在我的测试代码中我有:
context.Response.RedirectToRoute(new { Controller = "C1", Action = "A1" });
在我的单元测试中(在单独的测试项目中使用 RhinoMocks),我可以使用以下方法获取传递给此方法的实际参数:
var actual = this.ResponseMock.GetArgumentsForCallsMadeOn(r => r.RedirectToRoute(new { Controller = "dummy", Action = "dummy" }),
options => options.IgnoreArguments())[0][0];
我可以在测试中创建我预期的参数:
var expected = new {Controller = "C1", Action = "A1" };
当我运行这个测试时,一切看起来都非常有希望。如果我将“实际”和“预期”都放在监 window 口中,我可以看到它们的值看起来相同,而且它们的匿名类型看起来也相同。
但是,当涉及到 Assert 时,Visual Studio 无法看到 Actual 上的属性,因此我实际上无法键入我的 Assert。如果我输入以下内容:
actual.Controller =
Visual Studio 只是说:
Can't resolve the symbol 'Controller'
我已经尝试了推荐用于转换为匿名类型的解决方案(例如 cast-to-anonymous-type ,但这只会引发以下异常:
{"[A]<>f__AnonymousType0
2[System.String,System.String] cannot be cast to [B]<>f__AnonymousType0
2[System.String,System.String]. Type A originates from '^My Assembly Under Test^, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location '^MyAssemblyUnderTest.dll^'. Type B originates from '^My Test Assembly^, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location '\^MyTestAssembly.dll^'."}
我曾尝试使用反射将属性从“实际”复制到新的匿名类型,但这也失败了。真希望我知道我的 Watch 窗口是如何做到这一点的......
所以,我所追求的是:
- 理想情况下,对我的“实际”执行断言以表明其属性符合预期的首选方式
- 或者,一种将我的“真实”转化为我可以阅读的东西的方法。
提前致谢
格里夫
最佳答案
终于解决了...答案在 stackoverflow 上(还有什么地方?)C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly
总结:
被测类(HttpModule 程序集)
context.Response.RedirectToRoute(new { Controller = "C1", Action = "A1" });
测试类(HttpModuleTest 程序集)
var actual = this.ResponseMock
.GetArgumentsForCallsMadeOn(r =>
r.RedirectToRoute(new { Controller = "dummy", Action = "dummy" }),
options => options.IgnoreArguments())[0][0];
var controllerProperty = properties.Find("Controller", false);
var actionProperty = properties.Find("Action", false);
var controllerProperty = properties.Find("Controller", false);
var actionProperty = properties.Find("Action", false);
string controllerValue = controllerProperty.GetValue(actual).ToString();
string actionValue = actionProperty.GetValue(actual).ToString();
然后你就可以执行你的断言了。
关于c# - 对返回匿名类型的 Response RedirectToRoute 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28549385/