8.3. Solution
We will implement the functionality to manage contacts by creating tests followed by implementation code to pass the tests. This will ensure that we cover all the cases and that future additions don't break existing tests. It makes sense to start with creating contacts so that we have a foundation to build on to browse, edit, and delete.
8.3.1. Create a Contact
First, we need a View to create a contact, so let's create a new test class called ContactControllerTests:
[TestFixture] public class ContactControllerTests { private ContactController controller; private Contact model; [SetUp] public void SetUp() { controller = new ContactController(); model = new Contact() { Email = "test@test.com", Name = "Julia Roberts", Dob = new DateTime(1967, 10, 28), Sex = Sex.Female }; } [Test] public void create_returns_view () { var result = controller.Create(); Assert.IsInstanceOfType(typeof(Contact), controller.ViewData.Model); result.AssertViewResult(controller, "New Contact", "create"); } }
In the code, we are testing that there is a Create action that returns a View. To make the test pass, we first create our Model:
public class Contact { public int Id { get; set; } public string Email { get; set; } public string Name { get; set; } public Sex Sex { get; set; } public DateTime? Dob { get; set; } }
We then need an enumeration for sex:
public enum Sex { Undefined = 0, Male = 1, Female = 2 }
Next, we create our ContactController and add a Create action to it:
public class ContactController ...
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.