Coding Custom Unit Tests Using the Unit Testing Framework
The Unit Testing Framework supports unit testing in Visual Studio. Use the classes and members in the Microsoft.VisualStudio.TestTools.UnitTesting namespace when you are coding unit tests. You can use them when you have written the unit test from scratch or are refining a unit test that was generated from code you are testing.
To help provide a clearer overview of the Unit Testing Framework, this section organizes the elements of the UnitTesting namespace into groups of related functionality.
Attribute elements, whose names conclude with the string Attribute, can be used either with or without the string Attribute. For example, the following two code examples function identically:
Elements Used for Data-Driven Testing
A code element decorated with one of the following attributes is called at the moment you specify. For more information, see Anatomy of a Unit Test.
AssemblyInitialize and AssemblyCleanup are called right after your assembly is loaded and right before your assembly is unloaded.
ClassInitialize and ClassCleanup are called right after your class is loaded and right before your class is unloaded.
For Test Methods
Unit tests can verify specific application behavior by their use of various kinds of Assert statements, exceptions, and attributes. For more information, see Using the Assert Classes.
The following attributes and the values assigned to them appear in the Visual Studio Properties window for a particular test method. These attributes are not meant to be accessed through the code of the unit test. Instead, they affect the ways the unit test is used or run, either by you through the IDE of Visual Studio, or by the Visual Studio test engine.For example, some of these attributes appear as columns in the Test Manager window and Test Results window, which means that you can use them to group and sort tests and test results. One such attribute is TestPropertyAttribute, which you use to add arbitrary metadata to unit tests. For example, you could use it to store the name of a test pass that this test covers, by marking the unit test with [TestProperty("TestPass", "Accessibility")]. Or you could use it to store an indicator of the kind of test it is: [TestProperty("TestKind", "Localization")]. The property you create by using this attribute, and the property value you assign, are both displayed in the Visual Studio Properties window under the heading Test specific.
As described in Using Publicize to Create a Private Accessor, you can generate a unit test for a private method. This generation creates a private accessor class, which instantiates an object of the PrivateObject class. The PrivateObject class is a wrapper class that uses reflection as part of the private accessor process. The PrivateType class is similar, but is used for calling private static methods instead of calling private instance methods.