NUnit
Another commiter at NHibernate has created a StringTokenizer class that mimics the one existing in Java. I suppose it works but I can see that for getting the token it uses a loop and a number of concatenations. Kludgy. I feel tempted to write a more efficient version that uses String.IndexOf() and String.Substring() but I feel worried whether my "enhancements" will break the code.
Enter NUnit (a pretty smart C# implementation of venerable JUnit). As from the Java documentation, it is clear what StringTokenizer is supposed to do, what I did is to create a number of tests that check how the class works, like this:
[TestFixture]
public class StringTokenizerUnitTesting
{
[Test]
public void SimpleStringWithoutDelimiters()
{
string s = "Hello world!";
StringTokenizer st = new StringTokenizer(s);
IEnumerator enumerator = st.GetEnumerator();
enumerator.MoveNext();
Assertion.AssertEquals("Can't get first token", "Hello", (string) enumerator.Current);
enumerator.MoveNext();
Assertion.AssertEquals("Can't get second token", "world!", (string) enumerator.Current);
Assertion.AssertEquals("Still thinking there are more tokens", false, enumerator.MoveNext());
}
}
Tedious but easy. And now I can mangle with confidence the code! As a matter of fact I did make a couple of mistakes (shame, shame, in a 12 lines method). Moreover, the tests tell other developers how the class is supposed to be used and work. My tests don't cover all the angles of StringTokenizer but as time goes by, other commiters or myself will add more tests, so the class will become more and more resilient. And last but even more significant, as I wrote the tests I started to mentally design the inner workings of the class. Cool stuff NUnit. I look forward to writing a lot of tedious and easy tests.