开发者

Unit Test for non existent generic argument

I'm wondering how (or if I need) to test a certain scenerio in my code that开发者_开发百科 involves a generic collection.

What I have is this:

// Function
private void Func(FieldInfo fieldInfo)
{
   if(fieldInfo.FieldType.IsGenericType)
   {
      // Only support List<> right now
      Type gen_type = fieldInfo.FieldType.GetGenericTypeDefinition();
      if(gen_type != typeof(List<>))
      {
         throw new 
            NotSupportedException("Only Generic List is supported at this time");
      }
      // Find the generic list type
      Type[] generic_types = fieldInfo.FieldType.GetGenericArguements();
      if(generic_types.Length <= 0)
      {
         throw new 
            NotSupportedException("Generic List type not found!");
      }
   }
}

My question is do I need to check for the length to be less than or equal to zero if I know the generic type is a list? Am I always guaranteed to have a generic type argument? If not, how would I test this (ie, get the exception to be thrown)?


Reading the MSDN page on Type.GetGenericArguments(), it seems that the only time that the method will ever return an empty array is if the represented type is not a generic type. Since you know that the type represented here is a generic type (namely either List or List<>), the method will always return either T, or a type object representing a generic parameter, having a value of true for the IsGenericParameter property.

In its current state, the generic_types array should never be empty. I would say no, you don't need to test for it, regardless whether you're talking about a unit test, or a simple guard statement as you have in the code above. It's not appropriate for a unit test because it boils down to one of two situations: Either you end up testing the framework (which we should assume is already tested by Microsoft), or you end up testing internal details of the implementation of your unit test, which is a testing anti-pattern. For a guard statement, you just shouldn't test for situations which should be impossible, if the immediate code is written properly. Runtime checks like this should be reserved for things that can happen at runtime depending on the environment, even if the immediate code is correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜