unit testing variable state explicit tests in dynamically typed languages
- by kris welsh
I have heard that a desirable quality of unit tests is that they test for each scenario independently. I realised whilst writing tests today that when you compare a variable with another value in a statement like:
assertEquals("foo", otherObject.stringFoo);
You are really testing three things:
The variable you are testing exists and is within scope.
The variable you are testing is the expected type.
The variable you are testing's value is what you expect it to be.
Which to me raises the question of whether you should test for each of these implicitly so that a test fail would occur on the specific line that tests for that problem:
assertTrue(stringFoo);
assertTrue(stringFoo.typeOf() == "String");
assertEquals("foo", otherObject.stringFoo);
For example if the variable was an integer instead of a string the test case failure would be on line 2 which would give you more feedback on what went wrong.
Should you test for this kind of thing explicitly or am i overthinking this?