Search code examples
regexunit-testingnunitcode-coveragedotcover

Code Coverage and Regular Expressions (dotCover)


I am using dotCover to check my code coverage. At one line i am using a regular expression to check if a given string is valid.

if (!Regex.IsMatch(value, @"[a-zA-Z\-]"))
    throw new NullReferenceException("value");

I have created a unit test that checks if my code works as expected.

But dotCover doesnt recognize my code as covered. Sure because i dont test it with every possible (not matching) character.

What is a good solution for that problem?


Solution

  • If you want to check that the string doesn't contain a character that is not an ascii letter or an hyphen, you can use one of these patterns:

    with a negated character class (search a character):

    if (Regex.IsMatch(value, @"[^a-zA-Z-]"))
    

    without (describe all the string):

    if (!Regex.IsMatch(value, @"^[a-zA-Z-]*$"))
    

    If you want to prevent empty strings too:

    if (Regex.IsMatch(value, @"[^a-zA-Z-]|^$"))
    

    or

    if (!Regex.IsMatch(value, @"^[a-zA-Z-]+$"))