Graduate Program KB

Unit Tests


Three Laws of TDD

1. You may not write production code until you have written a failing unit test
2. You may not write more of a unit test than is sufficient to fail, and not compiling is failing
3. You may not write more production code than is sufficient to pass the currently failing test

Keeping Tests Clean

  • It is important in the long term to use good variable names and take care when writing your tests.
  • This makes it easier to maintain and debug as code evolves.
  • Tests should evolve with the production code.
  • Dirty tests are just as bad as no tests, they will frustrate people and slow things down.

Tests Enable the -ilities

  • Unit tests are what keep our code flexible, maintainable,and reusable.
  • Without tests changing code can result in unexpected bugs.
  • Unit tests alleviate fear of change.

Clean Tests

  • Readability is what makes our tests clean.
    • Clarity, Simplicity, and Density of Expression are what makes tests readable.

Domain-Specific Testing Language

  • Rather than using some API that a programmer uses to manipulate the system, we build up a set of functions and utilities that make use of the API.
  • Doing this results in the tests being more convenient to write and easier to read.
  • These functions and utilities become a specialised API used by the tests.
    • They are a testing language that programmers use to help themselves write their tests and to help those who must read those tests later on.

Dual Standard

  • Testing code does have a different set of engineering standards than production code.
  • It must still be simple, succinct, and expressive, but it need not be as efficient as production code.
  • We don't deploy our test suite.
  • There are things that you might never do in a production environment that are okay in a test environment.
  • They tend to involve issues of memory and CPU efficiency but never issues of cleanliness.

One Assert Per Test

  • Every unit test should ideally have one assert statement.

  • This basically comes down to each unit test testing one thing, one piece of functionality.

  • Links back in to the the Single Responsibility Principle, think of a unit test like a function.

  • This ties into single concept per test, same thought process as above.

F.I.R.S.T

  • Clean tests follow five other rules as well:
    • Fast: Tests should be fast, we won't be encouraged to run tests if they're going to take too long.
    • Independent: Test shouldn't depend on each other.
    • Repeatable: Tests should be repeatable in any environment.
    • Self-Validating: Test should have a boolean output, pass or fail. Otherwise failure can be subjective.
    • Timely: Tests need to be written in a timely fashion. They should be written just before production code.

Return