MSTest Attributes

My last post entailed differences between NUnit and MSTest. In this one I shall go over few attributes in MSTest. These attributes are:
  1. Test Class
  2. Test Method
  3. AssemblyInitialize
  4. AssemblyCleanUp
  5. ClassInitialize
  6. ClassCleanup
  7. Ignore
  8. TestCategory
  9. Timeout
  10. Description

Let's create a Unit test Project with the "UnitTest1.cs" as below:





[TestClass] This marks a class as the class that contains the test methods. The methods above Test1 and Test2 need to be annotated with attribute [TestMethod] so that they are identified as a test methods. On building the solution and running the tests they are shows as below with output in the test Explorer window






























The methods marked as [TestInitialize] will execute before every method and the method marked as [TestCleanup] executes after every test method. Similarly [ClassInitialize] executes before execution if the class containin the test methods and [ClassCleanup] after the test methods and test cleanup has run.
Note: The ClassInitialize method should be public,static and should have TestContext 
parameter. For ClassCleanup TestContext is not required
[Timeout(2000)] sets the time limit for the execution of the test method .If the execution takes more time than the limit specified here then the below error will pop-up.









Now in the same project create a new class "class1.cs" with the code as below:








Just as ClassInitialize and ClassCleanup AssemblyInitialize executes before ClassInitialize and AssemblyCleanup after ClassCleanup. Now build the solution and execute, the output is as below:












Note: The AseemblyInitialize method should be public,static and should have TestContext 
parameter. For AseemblyCleanup TestContext is not required.

Now create a new class "UnitTest2" with code as below:
Now the tests can be categorized as you can see above using the attribute [TestCategory]. A test can be skipped by marking it as [Ignore]. A test can be assigned more than 1 category as well as a description. Now on building the solution and run the ouput will be as  below:

















That's all !!!!

Comments

Popular Posts