Two questions about unit tests.
-
I’ve been writing unit tests for
a while, however they’re usually to
test classes I already had written.
Recently I read an article
(mind you an old article) that says
you should write unit tests before
you begin writing your code.Does anyone actually follow this
methodology? It seems like a good
idea on paper, but in practice is
it? - Should you write unit tests to see how your method handles bad/malicious input? Obviously you would want to write tests against functions which are specifically meant to handle “user” input to see how it handles bad/malicious input, but what about functions which should never have this type of input passed to them? At what point do you draw the line?
The methodology of writing unit tests before the classes is called Test-Driven Development (TDD) and was popularized by Kent Beck in the early 2000s. The idea is that you write a test that describes the functionality that you need. Initially, this test will fail. As you write your class, the test passes. You refactor your test to add more desired functionality, then refactor the class to make this new test pass. Your class has met its goals as soon as the tests pass. Of course, this scales up beyond classes as well.
As to what types of tests to write, it depends on if you are testing a public API or a private API. Public APIs should have more extensive tests written to ensure that input is well formed, especially if you don’t fully trust the users of your API. Private APIs (methods that are only called by your code) can probably get away without these tests – I would suspect that you can trust your own development team to not pass in bad data to them.