Throughout this book, we created tests for our ASP.NET MVC code. This appendix provides you with a brief introduction to unit testing frameworks.
Following are several popular unit testing frameworks for the .NET framework:
• Visual Studio Unit Test—Included with Visual Studio Professional and above
• NUnit—Open source testing framework available from NUnit.org
• xUnit.net—Open source testing framework available from xunit.CodePlex.com
This book uses the Visual Studio Unit Test framework because it is included with Visual Studio. In other words, using Visual Studio Unit Test does not require any special setup, and my goal is to keep things as simple as possible for you, the reader.
However, there are some significant drawbacks to using Visual Studio Unit Test. First, Visual Studio Unit Test is not included with the free version of Visual Studio: Visual Web Developer. To use Visual Studio Unit Test, you must purchase Visual Studio Professional or above.
Second, Visual Studio Test was not designed to make creating unit tests easy. Visual Studio Unit Test wants you to spin up a web server when you run tests against a web application. So, when using Visual Studio Unit Test, you must be careful to avoid doing what it tempts you into doing.
This chapter demonstrates how you can create and run unit tests by using two unit testing frameworks: the Visual Studio Unit Test framework and the NUnit framework.
When you create a new ASP.NET MVC application, you are prompted to create a new test project at the same time (see Figure B.1). The default unit testing framework is Visual Studio Unit Test.
If you select the option Yes, Create a Unit Test Project (and you should always select this option), then Visual Studio adds two projects to your solution: the ASP.NET MVC Web Application project and the Unit Test project.
The Unit Test project contains a Controllers folder that contains sample unit tests for the Account
controller and Home
controller. If you want to create tests for additional controllers, you can add your unit tests to the Controllers folder.
There are two ways that you can create a new test. First, you can create a new unit test by following these steps:
Product
controller, create a test named ProductControllerTests
.Don’t select the menu option Add, Unit Test. This option launches the Create Unit Tests dialog that generates tests that spin up a web server.
Completing these steps results in the test class in Listing B.1.
There is a lot of code in Listing B.1 that we don’t need. After I create a new test, I always immediately remove all this unnecessary code so that the test class looks like Listing B.2.
The other method to create a test is to simply add a new class to your test project. Follow these steps:
ProductControllerTests
and click the Add button.TestClass
attribute to the new class.When the red bar appears below the TestClass
attribute, press the keyboard combination Ctrl+. (Control key and period) and import the Microsoft.VisualStudio.TestTools.UnitTesting
framework (see Figure B.3) by pressing the Enter key.
After you complete these steps, you end up with the test class in Listing B.3.
There are three main attributes that you use when building unit tests:
• TestClass—
Marks a class as a class that contains test methods
• TestMethod—
Marks a method as a test method
• TestInitialize—
Marks a method that is run immediately before each test method
The Visual Studio test runner uses the TestClass
attribute to find classes that contain unit tests. Next, the test runner executes each public method decorated with the TestMethod
attribute.
You might want to perform some type of initialization before running each of your tests. For example, you might want to create a fake repository that contains a set of fake database records. In that case, you can mark a method with the TestInitialize
attribute that contains the logic for initializing the fake repository.
For example, the test class in Listing B.4 contains tests for a MathUtility
class that adds numbers.
The test class contains two test methods named AddPositiveNumbers()
and AddNegativeNumbers()
. The test class also contains an Initialize()
method that initializes the MathUtility
component being tested. The Initialize()
method re-creates the MathUtility
immediately before each test is run so that the results of each test are isolated.
You are not required to use the TestInitialize
attribute. You could repeat your test setup logic in each test; however, that would be ugly and would lead to un-maintainable test code.
Tests normally end with an assertion. A test asserts that something is true.
In this book, we concentrate on state verification tests. State verification tests end with assertions about the state of your application after a certain action. But other types of test, such as behavioral verification tests, don’t necessarily make an assertion about state.
The Visual Studio Unit Test framework includes three types of classes that you can use to perform assertions:
• Assert—
The main class for performing assertions.
• CollectionAssert—
This class contains specialized assertion methods for collections of objects.
• StringAssert—
This class contains specialized assertion methods for strings.
In most cases, you use the Assert
class. For example, you use Assert.AreEqual()
to assert that an actual value is equal to an expected value. You use Assert.IsInstanceOfType()
to assert that a particular object is a certain type (an instance of a particular class).
If you are working with a collection, you can use the CollectionAssert
class. For example, the CollectionAssert.AreEqual()
method enables you to verify that two collections have the same items in the same order. The CollectionAssert.AreEquivalent()
verifies that two collections have the same items, but not necessarily in the same order.
Finally, the StringAssert
class enables you to make assertions about strings. For example, the StringAssert.Contains()
method enables you to verify that a string has a particular substring. The StringAssert.Matches()
enables you to verify that a string matches a particular regular expression pattern.
Visual Studio provides you with four options for running tests:
• Run Tests in Current Context
• Run All Tests in Solution
• Debug Tests in Current Context
• Debug All Tests in Solution
The context is determined by the location of your cursor. For example, if you have clicked a test named VerifyUnitsInStock()
and you select the option to run tests in the current context, then only the VerifyUnitsInStock()
test runs. On the other hand, if you select an area of the test class outside any test method, then every test method in the test class runs.
Running tests in debug mode is useful when you need to set breakpoints in your test methods. Sometimes, just like any other application code, your test code fails to work for a mysterious reason. You can set breakpoints and run your tests in debug mode to try to figure out what is actually happening.
You can run your tests from the Test Tools toolbar (see Figure B.4). This toolbar should appear automatically when you have any file in your test project selected. If it does not appear, you can open this toolbar by selecting the menu option View, Toolbars, Test Tools.
A better option for running your unit tests is to use the keyboard. You can use the following keyboard combinations to run your unit tests:
• Ctrl+R, T—Run all tests in context
• Ctrl+R, C—Run all tests in class
• Ctrl+R, N—Run all tests in namespace
• Ctrl+R, A—Run all tests in solution
• Ctrl+R, Ctrl+T—Debug tests in context
• Ctrl+R, Ctrl+C—Debug tests in class
• Ctrl+R, Ctrl+N—Debug tests in namespace
• Ctrl+R, Ctrl+A—Debug tests in solution
The nice thing about using the keyboard to run your unit tests is that you do not need to be in your unit test project to use these keyboard combinations. You can run your tests using these keyboard combinations while you have a file from your ASP.NET MVC project open in the code editor.
When you run your tests, your tests appear in the Test Results window (see Figure B.5). You can double-click a test to view details on a particular test result. For example, if you run the test in debug mode, you can view a stack trace for a failing test.
By default, Visual Studio records and saves the results of up to 25 test runs. It saves the test results, and a copy of the assemblies being tested, in a folder named TestResults. This folder can get large (see Figure B.6).
There is a simple way that you can fix this problem. You can limit the number of test runs that Visual Studio records by selecting the menu option Tools, Options, Test Tools, Test Execution (see Figure B.7). Change the Limit Number of Old Test Results setting from 25 to 1. Modifying this setting causes Visual Studio to save only one test result. (Unfortunately, you can’t set this property to zero.)
Instead of using the Visual Studio Unit Test framework, you can use NUnit. The NUnit framework is compatible with both the full version of Visual Studio and the free Visual Web Developer.
You download NUnit from the following address:
Installation is straightforward. The MSI version of the NUnit download launches a wizard that walks you through the installation process (see Figure B.8).
After you install NUnit, you can create a separate class library project that contains your unit tests. You can follow the same procedure regardless of whether you use the full version of Visual Studio or you use Visual Web Developer.
You must have Visual Web Developer 2008 Service Pack 1 to create ASP.NET MVC applications and class library projects.
MvcApplication1.Tests)
and click the OK button.After you create the test project, you need to add two references to the project. First, you need to add a reference for the ASP.NET MVC application to the test project. Follow these steps:
Next, you need to add a reference to NUnit. Follow these steps:
Imagine that you want to test a class in your ASP.NET MVC project named MathUtility
. In that case, you can follow these steps to create a set of tests for this class:
MathUtilityTests
and click the OK button.The NUnit test class in Listing B.5 is similar to the Visual Studio Unit Test class in Listing B.4. The attributes have slightly different names, but they work the same. When creating an NUnit test, you typically use the following attributes:
• TestFixture—
Marks a class as a class that contains test methods
• Test—
Marks a method as a test method
• Setup—
Marks a method that is run immediately before each test method
NUnit includes a GUI test runner that you can use to run your tests. You open the GUI test runner by selecting Start, All Programs, NUnit, NUnit (see Figure B.11).
After the program starts, you need to open the assembly (DLL file) generated by your test project. Select the menu option File, Open Project and browse to the BinDebug folder of your test project. Select the assembly generated by your test project—for example, MvcApplication1.Tests.dll—and click the Open button (see Figure B.12).
If you select the menu option Tools, Settings and select Visual Studio under IDE Support, you can enable Visual Studio support. When Visual Studio support is enabled, the Open Project menu option enables you to open Visual Studio projects and solutions instead of assemblies.
After you load the test project assembly, you can run your tests by clicking the Run button. You can use the tree view to specify exactly which tests to run. For example, if you select the top node in the tree, then all of your tests are run.
Figure B.13 illustrates what happens when you run two tests. The first test failed and the second test passed.
3.145.97.104