Wednesday, 18 March 2009

Unit tests for c# and Visual Studio

I think most people agree that unit tests are good. You can complain that they are not enough, that sometimes you need to test more than, well, a unit, but at the end you have to agree that it's better to use them than not to use them.
Since c# is Object Oriented - you have classes objects, all the good stuff, you do have units and you can test them.
To do unit test in Visual Studio I use NUnit framework.

After you'll download the framework you'll need a project to test. I'll use my Person class, created for previous tutorials:

I've added introduceYourself method that we will test using NUnit. To be able to use NUnit framework you need to add reference to it in your project. Right click on References and Add. Brows to the bin directory of installed framework and choose nunit.framework.dll.
After that you can use NUnit.Framework in your testing class. Let's create a testing class:

You tell NUnit that your class is a test class by adding [TestFixture()] before class definition. You define testing methods by adding [Test()] before their definition. introduceYourself is a very simple test of a very simple method - it gives a parameter, and checks if result is as expected.
Now lets run our test. Build the project. Go to your NUnit installation directory and run NUnit application. Choose File->Open new Project, and navigate to your project's .exe file (will find it in project's bin directory).
When you open it you'll see your test on the left side of nUnit window:

Now, all you have to do is run yor test: select introduceYourself method and click "Run" button on the right.

Lot's of green means it's all good - your test is passed. The Console.Out tab will show you what your method put on the Console output.

No comments:

Post a Comment