Unit Tests are Tests
James Carr writes:
Unit Tests are NOT “tests” in the classical sense… they instead should be used to drive your design, to help you think about how the system you are writing should work, to illustrate functionality.
I disagree with the all caps “NOT”. I think unit tests are primarily for testing, and are particularly valuable for regression testing. I do find that writing tests as I write code influences and usually improves design, but they certainly are “tests”. The fact that tests can drive your design and illustrate functionality are often nice side effects, but they are not the primary reason I write tests.
He goes on to write:
If you ever find yourself running a code coverage tool after writing fresh code, step back and realize that you’re doing it wrong.. my suggestion is if you run a code coverage tool and find parts of your freshly written code aren’t covered, delete that code and try again.
Deleting and rewriting code is a bit too extreme for my taste, but I often do something similar. When fleshing out new work, I’ll often write new classes and interfaces, bounce ideas off coworkers, and rename / refactor heavily. Once I feel like I’ve found the right approach, I will sometimes comment out blocks of code, write a quick unit test (that fails), and then replace the code.
While I am developing Web Services Within Netbeans , i do benefit from JUnit Tests greatly , and agree with the idea that unit test should be treated as pre-processors instead of post-processing.
Regards.
I agree with James’ approach 100%, but it is probably because my style is TDD. It wasn’t always TDD, but styles change as influences change you. Before, I had an approach that worked for me. Now, I also have an approach that works for me, and that I prefer. To each his own. If your style, your habit, isn’t TDD, then… That’s that. Having changed my thought process to be inclined to using tests to discover better APIs, I don’t think my old style led to better code from me. It should be possible to get intimately comfortable with both approaches and objectively ask yourself which you like better. For me (as for James), it is TDD.
Thanks for the reply Eric! Indeed… to each his own when it comes to TDD. I used to regard unit tests as tests, even when doing TDD, but for myself personally when I found myself switching focus from “testing” to “providing an examples” I had a pretty good Zen moment.
I’ll expand on this in an upcoming post.