1

I am looking into the best ways to unit test my MVC 3 controllers. I was thinking of taking the result of viewresult on executing the controller action with a bunch of different params, serializing it and saving to file as a base for future tests.

2 questions:

  1. Is this a bad idea? for prior applications this would seem one of the safest ways to check that a change has not broken anything. I could deserialize my stored results, make any necessary changes and then compare to live results.
  2. If its a good way of testing, how can i serialize the viewresult? In the code below i get an error that the ActionResult cannot be serialized.
//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;
Conan
  • 3,074
  • 1
  • 22
  • 24

1 Answers1

0

The easiest way to test your controller actions is to examine the view model. You really should not need to be writing things out to files etc.

YOu can just do something like

Given an action of:

public ViewResult AddNewDocument(int documentFolderId)
    {
        var documentFolder = documentFolderRepository.Get(documentFolderId);

        return View("AddNewDocument",
                    new AddNewDocumentView { DocumentFolderId = documentFolder.Id, DocumentFolderName = documentFolder.Name });
    }

Write a unit test of (in mspec though the same holds true of NUnit or 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;
}

The point is the viewmodel that you pass to the view contains all the data you need to test. This can be grabbed directly from result.ViewData.Model.

Pat Hastings
  • 412
  • 4
  • 14