At the base of the testing pyramid[1] are unit tests. Unit tests test one unit of code at a time—usually one function or method.

Often, a single unit test is designed to test one particular flow through a function, or a specific branch choice. This enables easy mapping of a unit test that fails and the bug that made it fail.

Ideally, unit tests use few or no external resources, isolating them and making them faster.

Unit test suites help maintain high-quality products by signaling problems early in the development process. An effective unit test catches bugs before the code has left the developer machine, or at least in a continuous integration environment on a dedicated branch. This marks the difference between good and bad unit tests: Good tests increase developer productivity by catching bugs early and making testing faster. Bad tests decrease developer productivity.

Productivity usually decreases when testing incidental features. The test fails when the code changes, even if it is still correct. This happens because the output is different, but in a way that is not part of the function's contract.

A good unit test, therefore, is one that helps enforce the contract to which the function is committed.

If a unit test breaks, the contract is violated and should be either explicitly amended (by changing the documentation and tests), or fixed (by fixing the code and leaving the tests as is).

While limiting tests to enforce only the public contract is a complicated skill to learn, there are tools that can help.

One of these tools is Hamcrest[2], a framework for writing assertions. Originally invented for Java-based unit tests, today

Read more from our friends at Opensource.com