views:

51

answers:

1

Hi folks,

I'm trying to mock an ASP.NET MVC2 Controller using Moq but I get an error because i'm trying to mock an non-overridable property. How should I be doing this, please?

NOTE: the controller I'm trying to mock up is the (abstract) ASP.NET MVC2 Controller ... not a custom controller. Why? I'm trying to test some custom controller extensions I have made. I don't actually have a custom controller class.

Code:

// My own test helper magic shiz.
httpContextBaseMock = MockHelpers.GetAnHttpContextBaseMock();

controllerContextMock = new Mock<ControllerContext>();
controllerContextMock.Setup(x => x.HttpContext)
    .Returns(httpContextBaseMock.Object);

controllerMock = new Mock<Controller>();
controllerMock.SetupGet(x => x.RouteData)
    .Returns(RestMockHelpers.MockRouteData().Object);

That last line fails with...

System.ArgumentException : Invalid setup on a non-overridable member: x => x.RouteData

So then I thought, I shouldn't be mocking the controllerContext, but just creating an instance of it.. like what REA_ANDREW did in his SO question ...

var controllerContext = new ControllerContext(_httpContextBaseMock.Object, 
    new RouteData(), new Mock<ControllerBase>().Object);

var controller = new Controller(); <-- Cannot do this.
                                       Controller class is abstract.

So i'm not sure if I need to make my own fake controller class, in some test helper utility that does nothing, but just inherits from Controller. Then instantiate that.

But I feel that it should be all done using mock's, instead of starting out with some, then making some instances...

I'm so confused :(


Update:

I was asked to explain what code i'm trying to test. I've got a custom ViewResult i've made and the constructor set a single string property. I'm just making sure that property is set.

// Act.
var myResult = new MyResult(controllerMock.Object);

// Assert.
Assert.NotNull(myResult);
Assert.AreEqual("controllerName", myResult.ControllerName);
A: 

Hey,

For tests, I create a test class controller inside the test class like:

protected class TestController : Controller { }

And then I have an isolated test class that I can use for the tests. Then you can use this TestController instance.

Brian