First of all, what are unit tests and why are they important? The meaning behind them is kind of given away in the name. They are designed to test individual features/components (a.k.a. units) of code to makes sure it is working the way it is supposed to. This helps eliminate external factors like other features affecting the one you want to test. Unit tests are used anywhere and everywhere whether you are aware that you are using them or not. I can say that we use them on a regular basis at work and I use them when writing any sort of software, even if I might not specifically think “Lets unit test this piece”. With unit testing being so important, I thought why not see if there are ways to improve them, and luckily Stormpath has a blog with tips on it that I found quite useful and intend to use in the future.
The first thing they suggest is to use a framework for testing such as Junit. To put it simply, these frameworks just make life easier. They help setup, organize, and run your tests and I cannot agree more that frameworks both make tests easier and help improve testing. Next on their list is to use test driven development. This basically means that your write the tests before you write the code. Assuming the tests are written based off requirement, this forces you to make sure you hit those requirements and it provides a more complete, modular product in the end. I generally agree with these, but I do believe there are times where this can be difficult. Sometimes the customer may not know what they want to end product to be. What happens if the design shifts in the middle of development? Then you might have to rewrite all of the tests. If possible however, test driven development is a good approach to use. They then suggest to check how much code you are covering. In other words, are you testing every line of the unit you are testing? If not, you are leaving yourself open to bugs. Stormpath discussed a couple of other suggestions as well, but they have one that I feel is particularly important, so I am going to devote my time to that one, which is to tests negative situations and edge cases. Sure, you’ve tested all of your code and it works as long valid data has been entered. However, your program doesn’t live under a rock, so it is going to be exposed all sorts of situations. This can include users putting in invalid data. You have no control over what they are going to do with it, so your program needs to be able to handle those situations. I would argue that testing edge and invalid tests cases might be more important than normal test cases, simply because you can probably predict how it will be have when the user stays in bounds, but who knows what could happen if they don’t.
Link:
https://stormpath.com/blog/7-tips-writing-unit-tests-java
From the blog CS@Worcester – README by Matthew Foley and used with permission of the author. All other rights reserved by the author.