Appendix B. Using a Unit Testing Framework

In This Appendix

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.

Note

I’m happy to report that Visual Studio 2010 includes an improved unit testing framework.

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.

Using Visual Studio Unit Test

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.

Figure B.1. Create Unit Test Project dialog

image

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:

  1. Right-click the Controllers folder and select the menu option Add, New Test.
  2. In the Add New Test dialog select Unit Test (see Figure B.2).

    Figure B.2. Add New Test

    image
  3. Enter a good name for your test. For example, if you create a test for the Product controller, create a test named ProductControllerTests.
  4. Click the OK button to generate the test.

Warning

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.

Listing B.1. ControllersProductControllerTests.cs (C#)

image

image

image


Listing B.1. ControllersProductControllerTests.vb (VB)

image

image


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.

Listing B.2. ControllersProductController.cs (Cleaned Up) (C#)

image


Listing B.2. ControllersProductController.cs (Cleaned Up) (VB)

image


The other method to create a test is to simply add a new class to your test project. Follow these steps:

  1. Right-click the Controllers folder and select the menu option Add, Class.
  2. In the Add New Item dialog, name your new class ProductControllerTests and click the Add button.
  3. Modify the class so that the class is public.
  4. Add a 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.

Figure B.3. Importing the UnitTesting namespace

image

After you complete these steps, you end up with the test class in Listing B.3.

Listing B.3. ControllersProductControllerTests.cs (C#)

image


Listing B.3. ControllersProductControllerTests.cs (VB)

image


Understanding the Test Attributes

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.

Listing B.4. ModelsMathUtilityTests.cs (C#)

image


Listing B.4. ModelsMathUtilityTests.vb (VB)

image


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.

Using Assertions

Tests normally end with an assertion. A test asserts that something is true.

Note

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.

Running the Tests

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.

Figure B.4. The Test toolbar

image

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.

Figure B.5. Viewing test results

image

Limiting Visual Studio Test Results

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).

Figure B.6. Lots of test runs clogging my hard drive

image

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.)

Figure B.7. Limiting the number of test results

image

Using NUnit

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).

Figure B.8. Installing NUnit

image

Creating an NUnit Unit Test Project

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.

Warning

You must have Visual Web Developer 2008 Service Pack 1 to create ASP.NET MVC applications and class library projects.

Follow these steps:

  1. Create a new ASP.NET MVC web application project.
  2. Select the menu option File, Add, New Project.
  3. Select the Windows project type and select the Class Library template (see Figure B.9).

    Figure B.9. Creating a class library project with Visual Web Developer

    image
  4. Provide a name for the class library (for example, 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:

  1. Select the menu option Project, Add Reference.
  2. Select the Projects tab.
  3. Click the OK button.

Next, you need to add a reference to NUnit. Follow these steps:

  1. Select the menu option Project, Add Reference.
  2. Select the Browse tab.
  3. Navigate to the folder where you installed NUnit and select the NUnit assembly (for example, C:Program FilesNUnit 2.5in et-2.0framework unit.framework.dll). See Figure B.10.

    Figure B.10. Adding a reference to NUnit

    image
  4. Click the OK button.

Creating a Test

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:

  1. Add a Models folder to your test project.
  2. Add a class to your test project by right-clicking the Models folder and selecting Add, Class. Name the new class MathUtilityTests and click the OK button.
  3. Enter the code in Listing B.5 into the new class.
  4. Build your solution by selecting the menu option Build, Build Solution.

Listing B.5. ModelsMathUtilityTests.cs (C#)

image


Listing B.5. ModelsMathUtilityTests.vb (VB)

image


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

Running Tests

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).

Figure B.11. The NUnit GUI test runner

image

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).

Figure B.12. Opening the test project assembly

image

Note

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.

Figure B.13. Running tests with the GUI runner

image

Note

NUnit also includes a console test runner, named nunit-console.exe, which you can use to run tests from the command line.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.106.233