views:

34

answers:

1

The topic says it all.

I'm guessing this is because of some missing setup related to MVC, but I'm very new to the world of http, asp.net and mvc, so I'm not quite sure what's wrong.

public class MyController : Controller {
    public ActionResult MyAction(MyModel model) {
        return View(model);
    }
}

var controllerMock  = new Mock<MyController>() {
    CallBase = true // without this, the call to View(model) returns null
};


/*
 * I've also tried this before calling the action:
 * 
 * controllerMock.SetFakeControllerContext();
 *
 * from http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx
 * But the same applies.
 **/

ViewResult result = controllerMock.Object.MyAction(new MyModel()) as ViewResult;
Assert.AreEqual("MyAction", result.ViewName); // ViewName etc is blank
+2  A: 

If you use mvccontrib for your tests you can try something like this:

var controller = new MyController();
var builder = new TestControllerBuilder();
builder.InitializeController(controller);

var actionResult = controller.MyAction(new MyModel());
ViewResult viewResult = actionResult.AssertViewRendered().ForView("");
//or
ViewResult viewResult = actionResult.AssertViewRendered().ForViewOrItself("MyAction");
Fabiano
I am using MvcContrib, but this didn't work with my mock.. builder.InitializeController(controllerMock.Object) doesn't throw, but action still returns blank
simendsjo
you don't need to mock your controller, because you are testing your controller and not your mock. (or is there a reason for mocking it, that I don't see? :-) )
Fabiano
@Fabiano: Very good point :) I tried without mocking it, with and without the TestControllerBuilder and the same with SetFaceControllerContext - still blank data for the view though.
simendsjo
I'm not sure, but the viewname of the result is always blank when you use return a view without specifying the viewName explicitly e.g. 'return View("SomeOtherView", model);' would result in your expected behaviour (result.ViewName == "SomeOtherView) but with return View(model); it will be blank.
Fabiano
edited answer with an alternative mvccontrib method
Fabiano
Hmm.. But ViewResult.View is null too.. How can I then test that the correct view was given?
simendsjo