Should you unit test the return value of Hardcode Properties?
Should we be testing values that we already know the answer to?
If a value is important enough to 开发者_StackOverflow社区be a dedicated hard code value then should should it be important enough of to change a test at the same time as the value? or is this just overkill?!
If by “hardcoded properties” you mean something like this (in Java):
int getTheAnswer() {
return 42;
}
Then you need to ask yourself—why not make it a constant? For example,
static final int THE_ANSWER = 42;
In such a case, you don’t need to unit-test it.
In all other cases, you should consider unit testing.
More context is required to answer your question. It just depends. Is your getXXX method called from another method that is under test? If so, then it's already tested. If not, what is the client doing? Does the method even need to exist?
If you were developing your code using TDD, then your unit test is what would have created the hardcoded property in the first place.
No, but a better question is why are you hardcoding values? I know sometimes you have system-wide config settings that rarely (or never) change, but ideally, even those should be configurable and so should be tested. Values that will NEVER change should still be accessed via well-named constants. If your system is still in early development, maybe you haven't built those components yet, so don't worry about testing them - yet. ;)
Hmm Ok I guess the exceptions might be math or physics constants.
Should we be testing values that we already know the answer to?
How do you know that? Someone might have changed the code, and as a regression, it returns something else now.
If those values are part of the public API you should test them.
And you should test them against the literal value, not a constant defined by the program you are testing (because those could have been changed in error).
// good
assertEquals( "Number", myClass.getType(1234));
assertEquals( "Number", MyClass.TYPE_NUMBER);
// not so good
assertEquals( MyClass.TYPE_NUMBER, myClass.getType(1234));
Apart from obvious points from other answers:
You might want to add also, an integration test to verify that your hardcoded values actually works and plays well with other components.
Sometimes you do needs to hard code values, i.e. when implementing interfaces that asks for a capability tests, something like
interface IDecoder { // in C#
bool SupportStreaming { get; }
}
Of course, when implementing the IDecoder interface above, you'd have to hard code a value for the SupportStreaming property.
But the important question would of course not be Weather the it returns the hardcoded value? but Weather the hardcoded value actually is the correct value? which is only relevant when doing integration testing and/or testing other units/methods that depends on the value.
I personally don't bother with testing anything that's declarative.
精彩评论