Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c# - Mocking The RouteData Class in System.Web.Routing for MVC applications

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

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

Creating a fake RouteData doesn't work either as the constructor is 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!

Any help on this would be most welcome.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...