The 5 unit testing guidelines

Albert Starreveld
VX Company
Published in
5 min readMay 30, 2019

--

A unit test is a small automated check. It checks a tiny bit of software. Unit tests can be written relatively easily and they run in a matter of milliseconds. They are commonly being triggered automatically when somebody submits code to a repository so that the quality of the software is being validated, automatically, before it’s deployed onto the production environment.

In reality, unit tests are often far from small. They’re often hard to maintain and it’s hard to understand what the code that’s being tested was supposed to do when a test fails. As a result, unit testing becomes a costly exercise that slows down the team and the test-results doesn’t really prove much.

The following guidelines describe how to write proper unit tests:

  • Unit tests have one assert per test.
  • Avoid if-statements in a unit test.
  • Unit tests only “new()” the unit under test.
  • Unit tests do not contain hard-coded values unless they have a specific meaning.
  • Unit tests are stateless.

Guideline №1.) One assert per test

Unit tests are supposed to be small. In reality, they often aren’t. Many codebases contain tests with multiple asserts that require big setups as a result. That makes it hard to judge their validity, and it becomes unclear when to create a new unit test, or when to add to an existing one. As a result, this kind of tests grow and grow:

--

--

Albert Starreveld
VX Company

Passionate about cloud native software development. Only by sharing knowledge and code we can take software development to the next level!