Unit and integration testing best practices

With the evolution of architectures, the importance of unit testing is growing with time. Having great unit tests is no longer a luxury. It's a necessity that ensures that you are able to continuously improve code, and have a safety net to fall back on.

It's important to treat your unit test code equally with your production code.

At the most basic level, your unit tests should adhere to the 4 Principles of Simple Design.

A software application is said to adhere to the 4 Principles of Simple Design if it does the following:

  1. Runs all tests: Unit tests are continuously written alongside source code and are run in continuous integration.
  2. Contains no duplication: There is as less duplication as possible in your code.
  3. Expresses the intent of programmers: The code is easy to understand. You make your tests readable by clearly highlighting the important values in the tests, and give good method names to your tests. Use frameworks such as Hamcrest Matchers, AssertJ, and JSON Path to write great assertions.
  1. Minimizes the number of classes and methods: Each of the elements involved is as small as possible—methods, classes, packages, components, and applications. You can keep your unit tests small by writing one condition per test. Also, keep the scope of your unit test as small as possible—typically a method, at most; a group of methods.

Here are some of the best practices that are specific to unit tests:

  • Tests fail only when there is a problem with the production code: If tests fail because of external dependency, for example, a change in the data in a database, the development team would lose confidence in the tests. Over a period of time, you would see that tests would rot, and the team would start ignoring test failures.
  • Tests should find all the important problems with the production code: Try and write unit tests for all possible scenarios—including exceptions.
  • Tests should run quickly: It's important that your test runs quickly. This would ensure that the developers are inclined to run tests often. This would also ensure that continuous integration builds run fast, and the developers get quick feedback. Launching a Spring context in a unit test is time-consuming. So, wherever possible, we prefer to run unit tests with mocking, without launching a Spring context.
  • Tests are run as often as possible: Make sure that you run your tests in continuous integration. As soon as the code is committed to version control, a build should be triggered and the test run. This would ensure that you are taking maximum advantage of the great unit tests that your team is writing.
..................Content has been hidden....................

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