Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 使用moq从mvc操作返回的视图为空_Unit Testing_Asp.net Mvc 2_Moq - Fatal编程技术网

Unit testing 使用moq从mvc操作返回的视图为空

Unit testing 使用moq从mvc操作返回的视图为空,unit-testing,asp.net-mvc-2,moq,Unit Testing,Asp.net Mvc 2,Moq,这个话题说明了一切 我猜这是因为缺少了一些与MVC相关的设置,但我对http、asp.net和MVC的世界非常陌生,所以我不太确定到底是怎么回事 public class MyController : Controller { public ActionResult MyAction(MyModel model) { return View(model); } } var controllerMock = new Mock<MyController>

这个话题说明了一切

我猜这是因为缺少了一些与MVC相关的设置,但我对http、asp.net和MVC的世界非常陌生,所以我不太确定到底是怎么回事

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
公共类MyController:Controller{
公共行动结果MyAction(MyModel模型){
返回视图(模型);
}
}
var controllerMock=new Mock(){
CallBase=true//如果没有此选项,对视图(模型)的调用将返回null
};
/*
*在采取行动之前,我也尝试过:
* 
*SetFakeControllerContext();
*
*从http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx
*但情况也是如此。
**/
ViewResult=controllerMock.Object.MyAction(新的MyModel())作为ViewResult;
Assert.AreEqual(“MyAction”,result.ViewName);//ViewName等为空

如果您在测试中使用mvccontrib,您可以尝试以下方法:

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

我正在使用MvcContrib,但这不适用于我的mock。。InitializeController(controllerMock.Object)不会抛出,但操作仍然返回blank。您不需要模拟控制器,因为您正在测试控制器,而不是模拟控制器。(或者有没有我看不到的模拟它的原因?:-)@Fabiano:很好的观点:)我尝试了不模拟它,有没有TestControllerBuilder,还有SetFaceControllerContext,但视图的数据仍然是空白的。我不确定,但是,如果使用“返回视图”而不明确指定视图名,则结果的视图名始终为空,例如“返回视图(“SomeOtherView”,model);”将导致您预期的行为(result.ViewName==”SomeOtherView),但返回视图(model);它将为空。嗯……但是ViewResult.View也为空。然后我如何测试是否给出了正确的视图?