9.3. Solution

We will start with our usual test to make sure that a View exists for us with the appropriate title setup:

[Test]
public void import_should_return_view()
{
    var result = controller.Import();
    result.AssertViewResult(controller, "Import Contacts", "import");
}

We then make the test work with this action in the ContactController:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Import()
{
     ViewData["Title"] = "Import Contacts";
     return View("import");
}

In our next test, we will make sure that either a string or an uploaded file is posted to the server. The uploaded file is part of the Request object and is in the Files collection, so we will access the file by calling Request.Files[0]. We need to add a mock for these objects for our test to work:

httpContext.Expect(h => h.Request).Returns(request.Object);
request.Expect(r => r.Files).Returns(files.Object);

The above objects are declared as follows:

private static Mock<HttpRequestBase> request;
private static Mock<HttpFileCollectionBase> files;

Here is the test:

[Test]
public void import_should_return_error_if_contacts_and_file_are_missing()
{
    var result = controller.Import(null);
    Assert.IsNotNull(result);
    Assert.IsInstanceOfType(typeof(ViewResult), result);
    controller.ViewData.ModelState
         .AssertErrorMessage("Import",
                             "You must enter some contacts or upload a file");
    result.AssertViewResult(controller,"Import Contacts", "import");
}

To make the test pass, we create the import action that handles the post and validates ...

Get ASP.NET MVC 1.0 Test Driven Development: Problem - Design - Solution now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.