Test Projects and Unit Tests In Visual Studio 2008

A quick thing about setting up test projects through Visual Studios… basically how to do so.

Add new Project -> Test (Project Types) -> Test Project.

Now the easiest way I’ve added actual tests is just to add a normal class. Say SomeClassTest.


using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class SomeClassTest()
{
   [TestMethod]
   public void SomeClass_CreateWithNull()
   {
   }
}

What is [TestClass]? Well that is an attribute you are adding to the class so that .net knows certain methods in it may be test methods. Guess what [TestMethod] does…

Ok so now I have a TestClass and TestMethod, now what? Well in the menu:

Test -> Windows -> TestView

You should see that your method now shows up on the list. Simple huh? If the method isn’t showing up on the list make sure it is:

  • Tagged with the [TestMethod] attribute
  • Contained in a PUBLIC [TestClass]
  • Public
  • void
  • Non static

If you have all of those and still nothing, right click the method name in the Test View and look at it’s properties. There is a property called “Non-Runnable Error”. This will tell you what you need to get it rolling.

All right, now you have everything set… so next? Simple, right click the method name in the Test View and you can either Run or Debug the test. If you just Run the test, the Test Results window will pop up and you’ll see the progress. If it passes, then yay. If not, it will give you things unhandled/expected exception, failed asserts, and expected exceptions. If you debug, the same happens except, CRAZY SURPRISE AHEAD!!!, you can step through it. Also, you can run multiple tests by selecting however many you want and running them.

There are some useful options in the test view. If you right click the column area, you can add columns such as Class Name to help with ordering. After all, you might have a bunch of methods that are named the same in different classes, which sucks. Another thing you can do is left click the down arrow to the right of the refresh button for group by options.

End Note: If you don’t recognize the word “attribute” that’s ok. Most likely you have seen the [Something] notation before if you have used web controls (Possibly winforms controls, no idea). Simply put, attributes are like attaching extra information to just about anything so that later on you can use that information at runtime to perform actions. With the use of reflection, you could, for instance, check for only specific properties on a class that you want to fill dynamically. Say you have a dataset with the “UserName” column and a User class with the property Name. If you wanted to fill that Name property normally you could do something like:


user.Name = dataset["UserName"];


but with relfection you could get the property info, check the properties for a the ones with a certain attribute, and match the value in the attribute to the column name.