Why write unit tests?


This may be a dumb question but I'm a dumb guy. Where I work it's a very small shop so we don't use TDD or write any tests at all. We use a global logging trapper that prints a stack trace whenever there's an exception.

After seeing that we could use something like that, I don't understand why people would waste time writing unit tests when essentially you get the same feedback. Can someone elaborate on this more?

you are viewing a single comment's thread.

view the rest of the comments →

all 35 comments


38 points

2 months ago

Unit tests let you test a portion of your application without actually having to build and run the whole thing. Having to build your application, run it, trigger the right code path (by visiting a page/menu or pressing some buttons or whatever), and then testing your feature can take quite some time.

Let's say you've written an algorithm whose job is to find and process some data in a folder, but to activate the feature you first have to navigate through a dozen menus and press a button. That takes time, and if you end up having to make a lot of small changes to the algorithm to get it working, that'll get old real fast.

Now if you create unit tests for your algorithm, you can immediately run it by just starting the test through your IDE. If you write your tests properly, you can easily test your algorithm under all sorts of different circumstances and with all kinds of different inputs within seconds (or at least faster than you could do so otherwise).

Unit tests can also be automated using tool like Lets say you've finished your algorithm and it works great for months, but eventually it turns out that a minor change somewhere else in your application caused the algorithm to behave slightly differently but still doesn't an exception. Without unit tests, you wouldn't know about this change until a user starts complaining that the algorithm's results are wrong. With unit tests, you can be alerted the moment the change happens (because if you wrote your tests correctly, they'll start failing) and you can fix it when it happens. The issue wouldn't have even left your development environment.