Search code examples
c++unit-testingenumsreinterpret-cast

Is it possible to pass a non-enum value as an enum function parameter?


I have a function that looks like this:

std::string SomeClass::convertStateToString(StateE state) const
{
  std::string stateAsString;
  switch (state)
  {
    case UNKNOWN:
      stateAsString = "UNKNOWN";
      break;
    case OFFLINE:
      stateAsString = "OFFLINE";
      break;
    case ENABLED:
      stateAsString = "ENABLED";
      break;
    case DISABLED:
      stateAsString = "DISABLED";
      break;
    default:
      stateAsString = "ABNORMAL";
      break;
  }
  return stateAsString;
}

Where StateE is defined as:

typedef enum
{
  UNKNOWN      = 0,
  OFFLINE      = 1,
  ENABLED      = 2,
  DISABLED     = 3
} StateE;

For unit testing purposes i want to feed some bad data to convertStateToString and verify that i get "ABNORMAL" back. Is this possible?

In other words, is it possible to pass a value outside the range of an enum as an in-parameter to a function where the signature of the function says the parameter is of the enum type?

After having experimented with pointers and reinterpret_cast, i'm almost ready to claim that the function convertStateToString can not under any circumstances return "ABNORMAL".

No method is too hackish!


Solution

  • You can write this in your unit test :

    convertStateToString(static_cast<StateE>(10));
    

    This will force your code to pass in the "default" of your switch/case.