The data fields of our column based database are mapped into a DataField class. On each data field object the GetValue<T>() method can be invoked.
If T is an illegal type an exception gets thrown. What type should I pass in my unit test, where I test if an exception gets thrown if I pass an illegal type? The next known illegal type which comes in my mind? Or is there an approach with some more abstraction?
public object GetValue<T>()
{
if (typeof(T) == typeof(string)) return ValueString;
if (typeof(T) == typeof(int?)) return ValueInt;
if (typeof(T) == typeof(double?)) return ValueDouble;
if (typeof(T) == typeof(DateTime?)) return ValueDateTime;
if (typeof(T) == typeof(bool)) return ValueBoolean == true;
var ex = new Exception("Following type is not supported: " + typeof(T));
Log.Error(ex);
throw ex;
}
So every type but those should throw this exception if they get passed. So I’d need a kind of dummy type, right?
At the moment my unit test looks like this:
[Fact]
public void If_T_is_illegal_type_an_exception_gets_thrown()
{
_dataField = new DataField(_params);
Assert.Throws<Exception>(() => _dataField.GetValue<Type>());
}
Remember that unit testing is trying to get through all code paths and ensuring correct behaviour. You should have 6 tests in total: one for each of the 5 valid types, and one with any other type (as you currently have) to cover the final code path. Not sure why you’d need something more abstract.
You may prefer to use explicit conversions and casting so that this becomes a compile time test rather than run time: http://msdn.microsoft.com/en-us/library/xhbhezf4(v=vs.100).aspx