我正在研究对我的MVC 3控制器进行单元测试的最佳方法。 我正在考虑使用一堆不同的参数来执行控制器操作的viewresult结果,将其序列化并保存到文件作为将来测试的基础。
2个问题:
//create viewresult to return to view
ActionResult viewResult = View(dv);
//save viewresult for future unit test comparisons.
//Save data as name of controller action and param value used
string fileName = logDir + "\\" + controllerActionName + tradeDate.ToString("MMddyyyy") + ".viewresult";
//serialze and save to file
System.IO.Stream stream = System.IO.File.Open(fileName,System.IO.FileMode.Create);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bFormatter.Serialize(stream, viewResult);
stream.Close();
//send viewresult to mvc3 view
return viewResult;
答案 0 :(得分:0)
测试控制器操作的最简单方法是检查视图模型。 你真的不应该把文件写到文件等。
你可以做一些像
这样的事情给出以下行动:
public ViewResult AddNewDocument(int documentFolderId)
{
var documentFolder = documentFolderRepository.Get(documentFolderId);
return View("AddNewDocument",
new AddNewDocumentView { DocumentFolderId = documentFolder.Id, DocumentFolderName = documentFolder.Name });
}
写一个单元测试(在mspec中虽然NUnit或MSTest也是如此:
public class when_AddNewDocument_GET_is_requested : given_a_DocumentController
{
Because of = () => result = documentController.AddNewDocument(documentFolderId);
It should_return_a_view_result_with_the_view_name_AddDocument = () => result.ViewName.ShouldEqual("AddNewDocument");
It should_have_a_view_model_of_type_AddNewDocumentView = () => result.ViewData.Model.ShouldBeOfType<AddNewDocumentView>();
It should_have_return_document_folder_id_in_view_model = () => ((AddNewDocumentView)result.ViewData.Model).DocumentFolderId.ShouldEqual(documentFolderId);
It should_have_return_document_folder_name_in_view_model = () => ((AddNewDocumentView)result.ViewData.Model).DocumentFolderName.ShouldEqual(documentFolderName);
static ViewResult result;
}
关键是您传递给视图的视图模型包含您需要测试的所有数据。这可以直接从result.ViewData.Model。
中获取