Tuesday, August 22, 2006

Unit Testing Do's and Dont's

Unit Testing is awesome and can be a huge help in validating that changes to code doesn't cause any problems anywhere else in the application. There are a few small guidelines to make sure you follow.

1. Unit Tests should be completely independent of each other. The order of tests is not gauranteed. Thus any setup code that happens all the time should be factored out into a function with the SetUp attribute. If the setup code happens on a lot of the tests, then create a private helper function that is called from each test to initialize values.

2. Unit Tests are good. Do them.

3. Name your unit test for what it is testing. Test1_GetFiles is not good. The test number is not important and can actually get confusing later when inserting new tests. TestGetFiles or Test_GetFiles is a good name. However, since only functions that have the Test attribute will show up in NUNit nameing it GetFiles is also useful.

4. Code that is in the function with the SetUp attribute should still be tested. If the SetUp is initializing a variable to an object or to a specific value, then have a test that just validates that the initialization worked. For Example:

int FilesExpected=0;
private void Initialize()
FilesExpected = 10;

public void TestNumberOfFilesExpected()
Assert.AreEqual(10, FilesExpected);

No comments: