Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Unit TEst code which uses String.IsNullOrEmpty?

Do you write two Unit Tests? One for value being Null and one for value being string.Empty? The similar for string.IsNullOrWhiteSpace()?

like image 558
Skorunka František Avatar asked Sep 30 '22 07:09

Skorunka František


2 Answers

Yes, you would typically want to test that all possible classes of inputs (null, empty, whitespace, non-whitespace) get the right outputs.

That means testing both alternatives for String.IsNullOrEmpty() and all three alternatives for String.IsNullOrWhitespace().

like image 145
Cristian Lupascu Avatar answered Dec 05 '22 06:12

Cristian Lupascu


Typically I'd use NUnit test cases to test these permutations. They'll give you coverage of the three different checks without duplicating your test code.

For example:

[TestCase("")]
[TestCase(null)]
public class SomeTest(string stringValue)
{
   Assert.Throws<ArgumentException>(()=> CheckIfNullOrEmpty(stringValue));
}

public void CheckIfNullOrEmpty(string val)
{
   if(string.IsNullOrEmpty(val))
   {
       throw new ArgumentException();
   }
}
like image 41
DavidWhitney Avatar answered Dec 05 '22 06:12

DavidWhitney