10.3. Solution
We start by creating a message controller and a test class. The message controller is currently empty, and in the test class, we will create our first test:
[TestFixture] public class MessageControllerTests { private MessageController controller; private Message model; [SetUp] public void SetUp() { controller = new MessageController(); } [Test] public void create_should_return_view() { var result = controller.Create(); result.AssertViewResult(controller, "Create New Message"); } }
The previous code will not compile until we create the Create action method in the controller:
[AcceptVerbs(HttpVerbs.Get)] [Authorize] public ActionResult Create() { return View(new Message()); }
Note the use of the Authorize attribute; this prevents unauthorized access to the Create action, since we only want logged in (authorized) users to create messages. The code now compiles, and the test fails. We make a small change:
[AcceptVerbs(HttpVerbs.Get)] [Authorize] public ActionResult Create() { ViewData["Title"] = "Create New Message"; return View(new Message()); }
and now the test passes. Next, we want to make sure that an error is returned if the message's name is missing. First, we will change the SetUp method to instantiate an instance of the model with valid values:
[SetUp] public void SetUp()
{ controller = new MessageController(); model = new Message() { Subject = "My newsletter subject", Name = "October newsletter", Text = "Hello subscriber", Html = "Hello <b>subscriber</b>" }; ...
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.