Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio
Introduction
This walkthrough shows you how to create an ASP.NET MVC application in Visual Studio. In this walkthrough, you will create and run the sample MVC application. Then you will customize the application by adding a controller and two views.
In addition, this walkthrough shows how to use test-driven development (TDD). In the walkthrough, you create a project that contains unit tests for the MVC application.
In order to complete this walkthrough, you will need:
-
Microsoft Visual Studio 2008. You cannot use Visual Web Developer Express Edition for this walkthrough.
-
ASP.NET MVC Preview 3. You can download this release from the Microsoft ASP.NET MVC page of the ASP.NET Web site.
Creating a New MVC Project
To begin, you will create a new project for an MVC Web application. Note that you are creating a Web application, not a Web site project.
To create a new MVC project
-
On the File menu, click New Project.
The New Project dialog box is displayed.
-
In the upper-right corner, make sure that .NET Framework 3.5 selected.
-
Under Project types, expand either Visual Basic or Visual C#, and then click Web.
-
Under Visual Studio installed templates, select ASP.NET MVC Web Application.
-
In the Name box, type a name for the project, such as "MVCProject". For this walkthrough, it is not important what you name the project.
-
In the Location box, enter the name for the project folder.
-
If you want the name of the solution to differ from the project name, type a name for the solution in the Solution Name box.
-
Select Create directory for solution.
-
Click OK.
The Create Unit Test Project dialog box is displayed.
Note
If you are using Visual Studio 2008 Standard Edition, the Create Unit Test Project dialog box is not displayed. Instead, the new MVC application project is generated without a test project.
-
Select Yes, create a unit test project.
By default, the name of the test project is the application project name with "Tests" added, but you can change the name of the test project if you want. In addition, by default the test project will use the Visual Studio Unit Test framework. For information about how to use a third-party test framework, see Adding a Custom Test Framework.
-
Click OK.
The new MVC application project and a test project are generated. (In Visual Studio 2008 Standard Edition, no test project is generated.)
Examining the MVC Project
The folder structure of an MVC project differs from that of an ASP.NET Web site project. The MVC project contains the following folders:
-
Content folder. For content support files. This folder contains the cascading style sheet for the application.
-
Controllers folder. For controller files. This folder contains the application's sample controller, which is named HomeController.
-
Models folder. For data model files (such as LINQ to SQL .dbml files) and data entity files.
-
Views folder. For view page files. This folder contains two subfolders: Home and Shared. The Home folder contains two example page views that are related to the home controller. The Shared folder contains the master page view for the application.
If you are using an edition of Visual Studio other than Standard Edition, a test project was also generated. The test project has a Controllers folder that contains the HomeControllerTest class. This class has a unit test for each HomeController action method (Index and About).
The newly generated MVC project is a complete application that you can compile and run without change. The unit test project is also ready to compile and run. For this walkthrough, you will add a controller and view, and you will add unit tests for those.
Adding a Controller
You will now add a controller to provide user-login functionality.
To add a controller to the MVC project
-
In Solution Explorer, right-click the Controllers folder, click Add, and then click New Item.
The Add New Item dialog box is displayed.
-
Under Categories, expand either Visual Basic or Visual C# (depending on your project), expand Web, and then click MVC.
-
Under Visual Studio installed templates, select MVC Controller Class.
-
In the Name box, type LoginController.
Note
The ASP.NET MVC framework requires controller names to end with "Controller", such as HomeController, GameController, or LoginController.
-
Click Add.
Visual Studio adds the LoginController class to the project.
Adding Views
Next, you will add two new views: a Login view and a Welcome view. To keep the views organized, you will first add a Login folder under the Views folder.
To add page-content views to the MVC project
-
In Solution Explorer, right-click the Views folder, click Add, and then click New Folder.
-
Name the new folder Login.
Note
Views must be put in a folder that is named after the related controller. For example, views that relate to LoginController must be in the Login folder.
-
Right-click the Login folder, click Add, and then click New Item.
-
Under Categories, expand either Visual Basic or Visual C# (depending on your project), expand Web, and then click MVC.
-
Under Visual Studio installed templates, select MVC View Content Page.
-
In the Name box, type Login.aspx.
-
Click Add.
The Select a Master Page dialog box is displayed.
-
Under Project folders, under Views, select Shared.
-
Under Contents of folder, click Site.Master, and then click OK.
-
Repeat steps 3-9, but name the page Welcome.aspx.
Prepare for TDD by Creating Action-Method Stubs
To apply TDD techniques to this project, you write the unit tests for action methods before you write the action methods themselves. However, you will need stubs for the planned action methods, namely Login and FormSubmit.
To add action-method stubs
-
Open the LoginController class and remove the Index action method, which you will not need.
-
Add the following code in order to create the Login action method.
Public Function Login()
Throw New NotImplementedException()
End Function
public ActionResult Login()
{
throw new NotImplementedException();
}
-
After the Login method, enter the following code to create the FormSubmit action-method stub.
Public Function FormSubmit(ByVal name As String, _
ByVal password As String)
Throw New NotImplementedException()
End Function
public ActionResult FormSubmit(string name, string password)
{
throw new NotImplementedException();
}
Adding Unit Tests for Action Methods
Next, you will add a controller test class that contains a unit test for each new action method.
To add unit tests for the action methods
-
In the tests project, right-click the Controllers folder, click Add, and then click New Item.
The Add New Item dialog box is displayed.
-
Under Templates, select Class.
-
In the Name text box, type LoginControllerTest.cs or LoginControllerTest.vb.
-
Click Add.
Visual Studio adds the LoginControllerTest class to the test project.
-
Open the LoginControllerTest class and enter the following code. This code defines the unit tests for the two action methods that you will finish later.
<TestClass()> _
Public Class LoginControllerTest
<TestMethod()> _
Public Sub Login()
' Setup
Dim controller As LoginController = New LoginController()
' Execute
Dim result As ViewResult = controller.Login() As ViewResult
' Verify
Assert.AreEqual("Login Page", result.ViewData("Title"))
End Sub
<TestMethod()> _
Public Sub FormSubmit()
' Setup
Dim controller As LoginController = New LoginController()
' Execute
Dim result As ViewResult = controller.FormSubmit( _
"User Name", "PassMe") as ViewResult
' Verify
Assert.AreEqual("User Name", result.ViewData("Name"))
Assert.AreEqual("Welcome", result.ViewData("Title"))
End Sub
End Class
[TestClass]
public class LoginControllerTest
{
[TestMethod]
public void Login()
{
// Setup
LoginController controller = new LoginController();
// Execute
ViewResult result = controller.Login() as ViewResult;
// Verify
Assert.AreEqual("Login Page", result.ViewData["Title"]);
}
[TestMethod]
public void FormSubmit()
{
// Setup
LoginController controller = new LoginController();
// Execute
ViewResult result = controller.FormSubmit(
"User Name", "PassMe") as ViewResult;
// Verify
Assert.AreEqual("User Name", result.ViewData["Name"]);
Assert.AreEqual("Welcome", result.ViewData["Title"]);
}
}
-
Save and close the file.
-
Press CTRL+F5 to run the unit tests.
The results are displayed in the Test Results window. The two new tests will fail, because the action methods have not yet been fully implemented.
Adding Action Methods to a Controller
You will now add code for two action methods. The first action method renders the Login view. The second method obtains submitted data from a form and renders the Welcome view. To keep this example simple, the example does not implement code for user authentication.
To add action methods to the controller
-
Open the LoginController class and replace the Login action method stub with the following code, which renders the Login view:
Public Function Login()
ViewData("Title") = "Login Page"
Return View()
End Function
public ActionResult Login()
{
ViewData["Title"] = "Login Page";
return View();
}
-
Replace the FormSubmit action method stub with the following code, which obtains data from a form and renders the Welcome view:
Public Function FormSubmit(ByVal name As String, _
ByVal password As String)
' TODO: Authenticate user.
ViewData("Name") = name
ViewData("Title") = "Welcome"
Return View("Welcome")
End Function
public ActionResult FormSubmit(string name, string password)
{
// TODO: Authenticate user.
ViewData["Name"] = name;
ViewData["Title"] = "Welcome";
return View("Welcome");
}
-
Save and close the file.
Adding Content to the Views
Next, you will add content to the new views.
To add content to the page-content views
-
Open the Login.aspx view and add the following content inside the Content element:
<h2>Log In Please</h2>
<form action="/Login/FormSubmit">
Login Name: <input type="text" name="name" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Submit" />
</form>
This markup defines some text boxes and a button that make up a login form.
-
Open the Welcome.aspx view and add the following content inside the Content element:
<h2>Welcome</h2>
<p>Welcome, <%= ViewData["Name"] %>.</p>
This markup displays the value of the Name field that is passed to the view.
-
Save and close the file.
Calling the Login View from the Master-Page Menu
You will now add an item to the master-page menu that calls the Login action method.
To call the Login action method from the master-page menu
-
In the Shared folder, open the Site.master file and locate the unordered list in the menu div element.
-
Add the following code to the end of the list:
<li>
<%= Html.ActionLink("Login", "Login", "Login") %>
</li>
Note
The ActionLink method is a helper method that links to an action method. It takes the following parameters: the text for the link, the name of the action method, and the name of the controller.
-
Save and close the file.
Testing the MVC Application
Finally, you can test the application.
To test the MVC application
-
On the Test menu, click Run, and then click All Tests in Solution to run the unit tests.
The results are displayed in the Test Results window. This time the tests pass.
-
Open the HomeController file and press CTRL+F5 to run the application.
The Index.aspx page is displayed, which includes the tabs that are defined in the master page.
-
Click the Login tab.
-
Enter a name and a password in the form, and then click Submit.
The Welcome page is displayed, which shows that your changes worked.
This walkthrough gives you a first look at working with an MVC application. From here, you might want to learn more about the ASP.NET MVC framework. The following list suggests topics for additional learning.
This topic is ASP.NET Extensions documentation and is unsupported by Microsoft. Blank topics are included as placeholders and existing content is subject to change in future releases.