Reputation: 18129
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!
Upvotes: 0
Views: 573
Reputation: 82026
I don't see the problem:
std::string convertStateToString(StateE state);
int main() {
std::cout << convertStateToString(StateE(30)) << "\n";
}
Outputs:
ABNORMAL
Upvotes: 1
Reputation: 3604
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.
Upvotes: 2
Reputation: 333
No matter in how many ways C++ tries to enforce proper type checking, it should still be possible to just take the address of a memory location and change its content. Ex: declare a variable of type StateE, get its address, write in it a value that is out of range, then pass it to the function. Probably the variable should be volatile.
Upvotes: 1