Is it necessary to unit test a value object, and how would you go about it?
Take for instance this object:
public class TeamProfile
{
public string Name { get; set; }
public int Wins { get; se开发者_StackOverflowt; }
public int Losses { get; set; }
public int Draws { get; set; }
}
The answer is an opinion. I would say NO. But such questions really arise in day to day work and I understand the question so let me give some more opinion:
I would judge based on specific situation. If you think "my unit test routines do test it all" (and rely on it) and you see any likelihood above routines could ever change towards something more sophisticated then the answer is YES. Questions like these I sometimes answer with YES only to find out after a while it was really overkill. Then on other occasions I judge "oh no man this is really overkill" only to find out later that there was an aspect I never thought of.
How to test it? As all test cases: Define input and expected result. Set it. Get it. Check whether get is what you've set.
There is an excellent article on Value Objects and their introduction and testing by Dan Bergh Johnsson http://www.infoq.com/presentations/Value-Objects-Dan-Bergh-Johnsson
For clarity I must reiterate that the example given is not a value object. http://martinfowler.com/bliki/ValueObject.html
It is specifically either a command, message or more likely a (DTO) Data Transfer Object As others have mentioned, the provided class has no behaviour to test.
I don't think it's "necessary" per se, but it does guard you in case you add logic to your setters at some point (for example: throwing exception when negative Wins/Losses/Draws are attempted, since you're not using unsigned ints).
How to test it? Simple: Call the setter, call the getter, verify that the value is what you stored, or the exception you expected is thrown.
I would test the functionality that is more than simple get/set. For example, value objects should override Equals and GetHashCode.
If you think of the unit test as a coded functional spec, that can help you think up the tests that are needed. (If you really have a functional spec, then that is a good source for determining unit tests.)
I do not test the short style properties. The code behind is automatically generated by the compiler so I don't see why I should test them.
Just keep in mind to add the missing test as soon as you change the sort signature.
It can be done, but totally useless IMO.
Value objects contain absolutely no logic, and so testing them is wasted effort (and just about all other tests will break if your value objects are broken, given that you never mock them).
精彩评论