Reputation: 9332
The question title really says everything, but I'll do my best to clarify things. Let's say I have the following object:
function MyObject() {
this.isAwesome = true;
// Other methods and property
}
var obj = new MyObject();
Now, when writing unit tests against this object, should I write a test that makes sure that the isAwesome
property defaults to true? Or is that too rigid of a test?
Upvotes: 1
Views: 2525
Reputation: 11026
It depends on whether the constructor is capable of changing that default value. I don't know what language this is you're writing, so I'll just wing it:
function MyObject(stopBeingAwesome) {
this.isAwesome = true;
if (stopBeingAwesome) {
this.isAwesome = false;
}
}
If this is the case, then you can test that logic. Otherwise, you're unit testing a basic language construct such as assignment.
Unit tests are supposed to test the contracts of a unit of code. That is, the same input should always result in the same output. In this case, your contract involves this.isAwesome
being true
when the object is finished being constructed. However, unless someone changes the implementation of MyObject
so that isAwesome
won't be true
, it's not necessary to test that. And, if someone does change the implementation, they'll have to modify the test too. Worrying about regression at this level means that you're afraid that your other tests won't successfully test the default behavior, and that your coworkers are code saboteurs who will gleefully modify your constructor's default behavior for no apparent reason without telling you and without running your integration test suite.
It may seem like I am against regression tests, but when a build takes 20 minutes on Jenkins, you start to be grateful that you decided not to test some things.
Upvotes: 1
Reputation: 5647
Only write the test if the variable isAwesome
is somehow part of the public facing portion of the class. If isAwesome
just affects the behaviour of the class, test instead for that behavior.
Typically, a variable like that should not be part of the public facing portion of the class. For clean code, the least that would be required is that the variable be private and have getter and setter functions. Test those functions.
Upvotes: 7
Reputation: 152576
Seems like a trivial test to write, and if there are significant ramifications if isAwesome
is false, then why wouldn't you write that test?
Think about this - suppose a different developer comes by 6 months from now and thinks - "I'll change it so the property is not set in the constructor - let the client decide if MyObject
is awesome or not".
Now all of the code that expects every MyObject
to be awesome may break. Wouldn't you want to know that such a change as made so you could decide if it was a valid change or not?
Upvotes: 1