5.3. Solution
We start off by creating a new test class — MessageControllerTest — and adding our first test:
[TestFixture] public class MessageControllerTest { private MessageController controller; [SetUp] public void SetUp() { controller = new MessageController();
} [Test] public void Create_Returns_View() { ActionResult result = controller.Create(); result.AssertViewResult(controller, "New Message"); } }
In order for the above code to compile, we have to create the MessageController class and add a Create method to it:
public class MessageController : Controller { [AcceptVerbs("get")] [Authorize] public ActionResult Create() { ViewData["Title"] = "New Message"; return View(); } }
The next test is as follows:
[Test] public void Create_Returns_Error_If_Name_Is_Missing() { var model = new Message() { Subject = _subject, Name = string.Empty, Text = _text }; var result = controller.Create(model); var errorKey = "name"; var errorMessage = "Name is required"; //assert results Assert.IsNotNull(result); Assert.IsInstanceOfType(typeof(ViewResult), result); controller.ViewData.ModelState.AssertErrorMessage(errorKey, errorMessage); Assert.IsInstanceOfType(typeof(Message), ((ViewResult)result).ViewData.Model); //asser that the ViewData.Model var outModel = (((ViewResult)result).ViewData.Model as Message); Assert.AreEqual(model.Subject, outModel.Subject); Assert.AreEqual(model.Name, outModel.Name); Assert.AreEqual(model.Text, outModel.Text); Assert.AreEqual("Login", controller.ViewData["Title"], ...
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.