Unit Tests – Best practices

What are unit tests?

A unit test is a piece of code written by a developer that executes a specific functionality (Class or function) in the code to be tested and asserts a certain behaviour or output.

TDD (Tests Driven Process) is not designed to find bugs, instead, it is a robust way of designing software components (“units”) interactively so that their behaviour is specified through unit tests. In other words, it is a way of defining the expected behavior of specific piece of code (Unit).

Best Practices

Unit tests must run entirely in memory

A fast execution of unit tests is primordial since they are run frequently and there is a high number of them. To ensure this property, unit tests should not include HTTP requests, database access or filesystem interactions. 

Performing one assertion per unit test

It is easier to find out what went wrong when there is only one assertion in the test, if many are present, later assertions will not be checked after a failed one.

Avoid unit tests that cause impact or with persistent output

Unit tests should always be runnable with the same conditions without intervention.

Maximized use of annotations

Annotations make the code more compact and improve readability.

Meaningful naming convention

If the function to be tested if called extractId(), the unit test would be testExtractId(). And if only part of the function is tested (to avoid multiple assertions), the unit test would be testExtractId_invalidUser().

Test coverage must be at least 80%

Use @Before or @BefoleClass instead of initializing inside the unit test

AssertionFailedError in the unit test does not have a very informative stack trace.

Use the “expected” attribute of the test instead of catching the exception yourself

@Test(expected = IOException.class).

Package naming convention

The package naming convention should always be directly the same as the one of the package of your implementation. This will make it more maintainable as it forms a pattern

Each unit test must be independent

Integrate unit tests with the build script so they will be executed within the production environment

about author

Abdeslam Toumi

abdeslam.toumi@rema-it.at

Software Developer

Leave a Reply

Your email address will not be published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.