Example 2 – mocking functions for testing
In the following example, we will take a look at mocking functions using what we have learned so far in this chapter. The application we will be building and testing is a simple to-do application. The to-do application simply allows a user to add text to a to-do, to overwrite all content.
We won’t be using an actual database, so we’ll imagine that this one exists and use the filesystem and program arguments instead. Our goal will be to create tests for this application where we can mock the database interactions. To achieve this, we will use functions as first-class citizens and type aliases for code readability.
The complete example can be found on GitHub: https://github.com/PacktPublishing/Functional-Programming-in-Go./tree/main/Chapter2/Examples/TestingExample
Let’s start by setting up our main structs. The two structs we will need are Todo
and Db
. The Todo
struct represents the to-do item, which will...