4
\$\begingroup\$

I'm writing unit tests for a library which parses colors from user input (example: the user input “#f00” gives a red color; the user input “60,100%,100%” gives a yellow color, etc.)

One of the conditions is that the method Parse returns null when there is actually nothing to parse, i.e. when the input is either an empty string or its length is inferior to four characters. Those are the two unit tests:

[TestMethod]
public void SubmitEmptyText()
{
    var actual = new ColorParser().Parse(string.Empty);
    Assert.IsNull(actual);
}

[TestMethod]
public void SubmitShortText()
{
    Assert.IsTrue(new[]{"#", "#f", "#ff"}.All(c => !new ColorParser().Parse(c).HasValue));
}
  • Is the second method doing too much?
  • Am I expected to create three method? Seriously?!
  • Is the usage of functional programming here justified, or should I instead stick to the most basic way to write the tests?
\$\endgroup\$
4

1 Answer 1

3
\$\begingroup\$

What you need is passing parameters to common test method and supplying it with informative error message.

    [TestMethod]
    public void SubmitShortText()
    {
        var colorCodes = new[] { "#", "#f", "#ff" };
        DoAssertion(colorCodes);
    }

    private void DoAssertion(string[] colorCodes)
    {
        var parser = new ColorParser();
        foreach (var code in colorCodes)
        {
            var hasValue = parser.Parse(code).HasValue;
            Assert.IsTrue(hasValue, string.Format("Failed to parse color code '{0}'.", code));
        }
    }

Parametrized tests are also supported in XUnit:

    [Theory]
    [InlineData("#")]
    [InlineData("#f")]
    [InlineData("#ff")]
    public void SubmitShortText(string code)
    {
        var parser = new ColorParser();
        var hasValue = parser.Parse(code).HasValue;
        Assert.True(hasValue, string.Format("Failed to parse color code '{0}'.", code));
    }

Tests will be executed one by one. Execution will be stopped on the first failed test.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ +1. You do not want the growing volume of test code to over-burden your ability to maintain it. Design, build, refactor, just as if it were as important as your "money" code. Because it is. \$\endgroup\$
    – radarbob
    Jun 4, 2013 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.