TDD: Does it make sense to test that constructors set properties?
[TDD newbie]
I have a class Car with properties Color an开发者_JAVA技巧d Brand.
Does it make sense in TDD to test that the constructor sets those properties? Or do I wait with testing (and implementing) this until I need it?
So, do I build tests like these:
(c#)
public class CarTests
{
public void Constructor_Should_Set_Color()
{
var car = new Car("Green", "Volvo");
Assert.Equals(car.Color, "Green");
}
}
Or do I wait until I have a use case scenario in which I must, for example, filter all green cars from a list that was built using the constructor, which will fail because the cars will have null as color ?
Does it really make sense to directly test constructors ? What about Equals() ?
Ideally, I think, you wouldn't even have a Color property until you needed it. At that point, you might just use a setter, or you might add it to the constructor, or add a new constructor. The second option leaves you in a state with two (or more) constructors - and you may find that's helpful; in many circumstances (for both tests and "regular" code) you may not care what color a car is. And that is test-driving your design.
If you're actually doing TDD, you won't have the properties Color and Brand until there's a test requiring their existence.
That test probably shouldn't be like your constructor test, but a test of something else that cares about Color or Brand.
It seems to depend on the circumstances and the perference of the developer / developer team, just like the question whether or not to have several different assertions in one test method.
While purists will likely want to go for near-100% test coverage, there are also developers who only test non-trivial stuff. The line between these two extremes is blurry.
I usually don't bother testing constructors and Equals, if they are not too complex. If they get more complex or I run into a bug then I add tests. Although this could be a signal that your class is getting too complex and is in need of refactoring, which can only bee done safely if you have your class protected by a safety net of tests.
From a test-driven perspective you probably wouldn't start with testing the constructor anyway. The need for the class or method would arise because of some scenario in which it's useful and should be tested in that context.
精彩评论