Failure of the RouteData class in System.Web.Routing for MVC applications

I am trying to test some application logic that depends on the Values ​​property in ControllerContext.RouteData.

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

Failure unit test: System.ArgumentException: Invalid setting to not override member: r => r.Values

Creating a fake RouteData does not work either as a RouteData constructor (RouteBase, IRouteHandler).

The important class here is the abstract RouteBase class, which has a GetRouteData (HttpContextBase) method that returns an instance of RouteData, the class I'm trying to fake. Taking me in circles!

Any help on this would be appreciated.

+27
c # asp.net-mvc moq
Jun 12 '09 at 11:30 a.m.
source share
2 answers

RouteData also has a constructor that takes no arguments . Just create it and add the values ​​it needs. No need to scoff at it when you can create it.

  var routeData = new RouteData(); routeData.Values.Add( "key1", "value1" ); var controllerContext = new ControllerContext(httpContextMock.Object, routeData, controllerMock.Object); 
+53
Jun 12 '09 at 12:01
source share

I am very new to TDD when combined with mock objects, but the lesson I learned at an early stage from a colleague was not to mock types that you don't own. Therefore, do not try to mock RouteData. The idea was originally conceived by Joe Walnes (although I cannot find where he said this).

+2
Jun 12 '09 at 12:23
source share



All Articles