Chapter 6. Leaving Nothing to Luck – Unit Tests and Acceptance Tests

In this chapter, we will see why and how our application should be tested. We will see the differences between unit tests and acceptance tests, and learn how to do both.

This chapter is divided in two parts. In the first part, we will write tests in Java while studying the different ways of testing. In the second part, which is shorter, we will write the exact same tests in Groovy, and see how we can improve our code readability with this awesome language.

If you do everything in this chapter, you will have double tests, so feel free to keep only the tests that are most readable for you.

Why should I test my code?

Working in the Java world has made a lot of developers aware of the importance of tests. A good series of tests can catch regressions early and allows us to be more confident when we ship our product.

A lot of people are now familiar with the notion of continuous integration (http://www.thoughtworks.com/continuous-integration). This is a practice where a server is in charge of building the application every time a change is made on the source control system.

The build should be as fast as possible and capable of self testing. The main idea of this practice is to get a fast feedback loop; you should get details about what went wrong as soon as something in the system breaks.

Why should you care? After all, testing your application is an additional cost; the time spent designing and maintaining tests will necessarily eat into some development time.

Actually, the later a bug is found, the costlier it gets. If you think about it, even a bug found by your QA team begins to cost more than a bug you find on your own. It forces you to switch back to the context you were in when writing the code: why did I write this line? What was the underlying business rule of that function?

If you write tests early on and are able to launch them in a few seconds, it will certainly cost less time to address potential bugs in your code.

Another benefit of tests is that they act as a living documentation of your code. While writing extensive documentation, and even code comments, can prove ineffective because they easily become outdated, forming the habit of writing a good test for limit cases or surprising behaviors will act as a safety net for the future.

What is this line of code for? Have you ever found yourself asking this kind of question? Well, if you have a good set of unit tests, you can just remove it and see what breaks! Tests give us an unprecedented confidence in our code and in our ability to refactor it. Software is very fragile. If you stop caring, it will slowly rot and die.

Be responsible—don't let your code die!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset