C# 为 MVC 应用程序模拟 System.Web.Routing 中的 RouteData 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/986183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mocking The RouteData Class in System.Web.Routing for MVC applications
提问by Magpie
I'm trying to test some application logic that is dependent on the Values property in ControllerContext.RouteData.
我正在尝试测试一些依赖于 ControllerContext.RouteData 中的 Values 属性的应用程序逻辑。
So far I have
到目前为止我有
// Arrange
var httpContextMock = new Mock<HttpContextBase>(MockBehavior.Loose);
var controllerMock = new Mock<ControllerBase>(MockBehavior.Loose);
var routeDataMock = new Mock<RouteData>();
var wantedRouteValues = new Dictionary<string, string>();
wantedRouteValues.Add("key1", "value1");
var routeValues = new RouteValueDictionary(wantedRouteValues);
routeDataMock.SetupGet(r => r.Values).Returns(routeValues); <=== Fails here
var controllerContext = new ControllerContext(httpContextMock.Object, routeDataMock.Object, controllerMock.Object);
The unit test fails with: System.ArgumentException:?Invalid?setup?on?a?non-overridable?member: r?=>?r.Values
单元测试失败: System.ArgumentException:?Invalid?setup?on?a?non-overridable?member: r?=>?r.Values
Creating a fake RouteData doesn't work either as the constructor is RouteData(RouteBase,IRouteHandler).
创建虚假的 RouteData 也不起作用,因为构造函数是 RouteData(RouteBase,IRouteHandler)。
The important class here is the abstract class RouteBase which has the method GetRouteData(HttpContextBase) which returns an instance of RouteData, the class I'm trying to fake. Taking me around in circles!
这里的重要类是抽象类 RouteBase,它具有方法 GetRouteData(HttpContextBase),它返回 RouteData 的一个实例,我试图伪造该类。带我兜兜转转!
Any help on this would be most welcome.
任何有关这方面的帮助将是最受欢迎的。
采纳答案by tvanfosson
RouteData also has a constructor that takes no arguments. Simply create one and add the values to it that you want. No need to mock it when you can create one.
RouteData 还有一个不带参数的构造函数。只需创建一个并向其添加所需的值。当您可以创建一个时,无需模拟它。
var routeData = new RouteData();
routeData.Values.Add( "key1", "value1" );
var controllerContext = new ControllerContext(httpContextMock.Object, routeData, controllerMock.Object);
回答by John Berberich
I'm very new to TDD in conjunction with mock objects, but a lesson I learned early on from a colleague was not to mock types you don't own. Thus, don't try to mock RouteData. The idea was originally conceived by Joe Walnes(though I can't find where he said it).
我对结合模拟对象的 TDD 非常陌生,但我很早就从同事那里学到的一个教训是不要模拟你不拥有的类型。因此,不要尝试模拟 RouteData。这个想法最初是由Joe Walnes构思的(虽然我找不到他在哪里说的)。