Monthly Archives: February 2013

Unit Testing with nUnit

10792282_sFirst, go to and watch the videos, then read the book: “The Art of Unit testning” (second edition)

Use NuGet to import nUnit into your project. Use code templates to work faster.

Follow these naming conventions:

  • Create a seperate project for the test classes – name it <yourprojectname>.UnitTests
  • Make a test class for each class you want to test – name them <ClassName>Tests
  • Each test method should be named like this:

The test method is structured into three stages

  1. Arrange (setting up the objects)
  2. Act (call the method to test)
  3. Assert (check the result)

Notice the difference between unit test and integration test:

  • A unit test is small, fast and easy to make and maintain. Checks if an individuel piece of code works. Every time you run the unit you will get the same result – even if you run it after a year (no configuration is required, no dependencies to e.g. external data, the system time or random numbers)
  • Intregration test are slower and more compleks. Typically checks if the integration between systems works as intended (Checks if several units actually works together)

Notice: nUnit has a very strong feature called TestCase – use it whenever it makes sense.

Testing for error exceptions

 var ex = Assert.Throws<ArgumentException>(() => foo.DoSomething() );
 StringAssert.Contains("Actual exception message", ex.Message);

Test runnners

I use the test runner provided with ReSharper, but you can use the built-in runner in Visual Studio, or the one provided with nUnit

Tips from Osherove

“Readability is one of the most important aspects when writing a test”

Best practice: Tests must run totally independent of each other