Unit testing is good

Recently Ayende added another spot-the-bug post. Usually I’m just curious how fast people find the problem.

Some time ago he also published few posts about how he does unit testing.

In “Scenario driven tests” he says that, as I understand it, it’s better to test a whole scenario not a single method. I’m okay with that, as long as scenarios are in reasonable numbers and code coverage is high.

In “Tests have got to justify themselves” he states “I am not using TDD.”

Well if you were you would not have so many problems in 10 lines of code, period.
You want to test scenarios ok, but when you’ve simple method with lots of logic, you are going to make a mistake at some point. Test it!

public static string FirstCharacters(this string self, int numOfChars)
{
    if (self == null)
        return "";
    if (self.Length < numOfChars)
        return self;
    return self
        .Replace(Environment.NewLine, " ")
        .Substring(0, numOfChars - 3) + "...";
}

Each of the following tests will fail:
(negative values are not reasonable input for such method, so we won’t go there)

[Test]
public void FirstCharacters_EmptyString_Truncates()
{
    Assert.AreEqual("", "".FirstCharacters(0));
}

[Test]
public void FirstCharacters_RegularString_Truncates()
{
    Assert.AreEqual("12345", "12345".FirstCharacters(5));
}

[Test]
public void Method_Condition_Result()
{
    Assert.AreEqual("...", "12345".FirstCharacters(2));
}

[Test]
public void FirstCharacters_StringWithNewLine_Truncates()
{
    Assert.AreEqual("  ", "rnrnrn".FirstCharacters(2));
}

[Test]
public void FirstCharacters_StringWithNewLine_Truncates2()
{
    Assert.AreEqual(" ...", "nnnnnnnn".FirstCharacters(4));
}

[Test]
public void FirstCharacters_StringWithNewLine_Truncates3()
{
    Assert.AreEqual("start end", "startnend".FirstCharacters(255));
}

Tags: ,

Questions?

Consider using our Q&A forum for asking any questions.