C# – Testing a Conversion Class

cunit testing

I have a class that is responsible for performing conversions from/to twenty-something types. Let's call this class ConvertUtils.

For C# programmers out there – this class expands .Net's Convert class.

It looks something like this:

public static class ConvertUtils {
    public static object ChangeType(object obj, Type newType) {
        if (conversionSupportedByFramework)
            return Convert.ChangeType(obj, newType);
        else
            ConvertSpecialCases(obj, newType);
    }
}

How would you go about testing it? I'm assuming we do need to black-box test this code.

The two ways we thought about, are:

  1. Writing 400+ unit tests – cover all to/from combinations that we can think of.
  2. Write tests only for the new conversions – the ones not supported by the Convert class – actually testing only the ConvertSpecialCases() function [which isn't our goal, as stated above]

The con of the first possibility is to have too many tests – which prolongs the build time, involves maintaining more code, etc.

The con of the second possibility is to not fully check the responsibility of the class –
what if a certain if statement decides to implement (wrong) custom logic, instead of letting Convert do it's job? e.g. just before if (conversionSupportedByFramework) someone decides to call some custom logic?

What do you think about this issue?

Best Answer

You don't have to test .NET Framework's code in your specific case, because:

  • You can't inherit from Convert class, since this class is static; even if you could do that, for example if Convert class weren't static:

  • The Convert class has no virtual methods,

  • There are no instance methods,

  • There are no abstract methods,

  • You cannot override static methods in a class,

  • You shouldn't hide methods by using new keyword anyway (and if you do, Code analysis will shout at you).

The only way you may be able to screw with existent functionality is through Reflection. If you use Reflection in order to play with the internals of the Convert class, then yes, you have to study and test the impact it may have.

Otherwise, you just have to test the new code you'll write in your custom class.

Related Topic