嘲讽的RouteData类的System.Web.Routing为MVC应用 [英] Mocking The RouteData Class in System.Web.Routing for MVC applications

查看:146
本文介绍了嘲讽的RouteData类的System.Web.Routing为MVC应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要测试一些应用程序逻辑是依赖于ControllerContext.RouteData Values​​属性。

I'm trying to test some application logic that is dependent on the Values property in ControllerContext.RouteData.

到目前为止,我有

// 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);

单元测试失败:
System.ArgumentException:无覆盖的成员无效设置:
R => r.Values​​

The unit test fails with: System.ArgumentException: Invalid setup on a non-overridable member: r => r.Values

创建一个假的RouteData无法正常工作,无论是作为构造函数的RouteData(RouteBase,IRouteHandler)。

Creating a fake RouteData doesn't work either as the constructor is RouteData(RouteBase,IRouteHandler).

这里最重要的类是抽象类RouteBase它有它返回的RouteData,我想假的类的实例方法GetRouteData(HttpContextBase)。带我转转!

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!

任何帮助将是非常欢迎的。

Any help on this would be most welcome.

推荐答案

的RouteData也有构造函数没有参数​​的。简单地创建一个和值,您要添加到它。没有必要嘲笑它时,你可以创建一个。

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.

 var routeData = new RouteData();
 routeData.Values.Add( "key1", "value1" );

 var controllerContext = new ControllerContext(httpContextMock.Object, routeData, controllerMock.Object);

这篇关于嘲讽的RouteData类的System.Web.Routing为MVC应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆