One of the things I struggle with the most when writing unit tests is what do I test and what do I not test.
So given the following code, what tests should I write:
public static class Enforce
{
public static T ArgumentNotNull<T>(T parameter, string parameterName) where T : class
{
if (parameterName.IsNullOrWhiteSpace())
throw new ArgumentNullException("parameterName");
if (parameter.IsNull())
throw new ArgumentNullException(parameterName);
return parameter;
}
public static string ArgumentNotNullOrEmpty(string parameter, string parameterName)
{
ArgumentNotNull(parameter, parameterName);
if (parameter.IsNullOrEmpty())
throw new ArgumentException(parameterName);
return parameter;
}
public static string ArgumentNotNullOrWhiteSpace(string parameter, string parameterName)
{
ArgumentNotNull(parameter, parameterName);
if (parameter.IsNullOrWhiteSpace())
throw new ArgumentException(parameterName);
return parameter;
}
public static T NotNull<T>(T instance) where T : class
{
instance.IfNullThrow<T, NullReferenceException>(String.Format(EnforceResources.TypeNotNull, typeof(T).FullName));
return instance;
}
}
}
Should I write a test for ArgumentNotNull<T>
that tests for the exception being thrown and then one that tests for the exception NOT being thrown? I guess my question is, should I write my tests that test for the expected and then the exact opposite?
[Fact]
public void ShouldThrowArgumentNullException()
{
object arg = null;
Assert.Throws<ArgumentNullException>(() => { Enforce.ArgumentNotNull(arg, "arg"); });
}
[Fact]
public void ShouldNotThrowArgumentNullException()
{
var arg = "Test";
Assert.DoesNotThrow(() => { Enforce.ArgumentNotNull(arg, "arg"); });
}