(Microsoft .NET,Microsoft ASP.NET,Microsoft Visual Studio)
by Jason Skowronek
on 02/03/2011
This article demonstrates how to setup a basic unit test project to take care of code coverage of a standard ASP.NET website.
This article assumes you have created an ASP.NET Web Application project (not ASP.NET Website).
Setup a Unit Test Project
- Open your solution in Visual Studio 2010
- Click Test | New Test
- Select Basic Unit Test (or any of the others)
- Name your test class
- Add to or create a new test project (preferably ProjectName.Tests)
Couple of caveats:
- Only works for ASP.NET 4.0 Web Applications
- You will need to remove any backwards compatible runtime assemblies from the web.config or you will get 500 errors. Best to add them to your web.config transforms if necessary.
<runtime xdt:Transform="Replace">
<assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
Example Test Class
This is a very basic test class and unit test method for example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;
namespace Project.Tests
{
[TestClass]
public class BusinessTests
{
[TestMethod]
[UrlToTest("http://localhost:8080/Default.aspx")]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("$(SolutionDir)\\Project.Web")]
public void TestMethod1()
{
string url = HttpContext.Current.Request.Url.ToString();
}
}
}A couple of things to note:
- UrlToTest: References the Visual Studio Development Server. IMHO, best to use a specific port (i.e. 8080) when using tests.
- AspNetDevelopmentServerHost: Microsoft recommends using the environment variable: %PathToWebRoot%. However, this can prove to be problematic when working in team environments. So in this example, we take advantage of the Visual Studio macro variable, $(SolutionDir) to fill the path to the solution regardless of the build environment.
Debugging ASP.NET Unit Tests
To debug your tests, you will need to attach to the worker process for your web application (either WebDev.WebServer... or w3svc), and NOT to the test project.
Once attached to the web debugger, you can then select the test method and click CTRL + R + T to run the selected test, or CTRL + R + A to run all tests.
Code, out!
References