12 Testing functional programs

 

In this chapter you will learn

  • how to test pure functions by providing examples
  • how to test pure functions by providing properties
  • how to test side effects without using any mocking libraries
  • how to develop new functionalities in a test-driven way

Beware of bugs in the above code; I have only proved it correct, not tried it.

—Donald Knuth

Do you have tests for that?

This last chapter of the book is devoted to one of the most important software engineering activities: testing. Tests are one of the major methods of writing maintainable software. They can be used to make sure the program behaves according to the requirements, it doesn’t have bugs we discovered earlier, and that it integrates with external APIs, services, or databases properly.

Having an application that consists mostly of pure functions that operate on immutable values makes writing tests a very enjoyable endeavor. The tests in this chapter are small and readable, and they cover a lot of production code.

On top of all that, we can also use tests to document the application: to help clarify the responsibilities and inner working to other team members. This is the best kind of documentation because it can’t get outdated as easily as normal text-based documentation usually does—assuming that the test itself is easy to understand. That all makes tests a very important element of well-developed, readable, and maintainable software.

Tests are just functions

Choosing functions to test

Testing by providing examples

Practicing testing by example

Answers

Generating good examples

Generating properties

Property-based testing

Testing by providing properties

What are shrinks?