Search⌘ K
AI Features

Mocking in Unit Tests

Explore how mocking in unit tests allows you to simulate dependencies and control their behavior in Go. Learn to write mocks for services, test multiple scenarios effectively, and ensure your tests focus on the software's behavior rather than external dependencies.

Mocking in unit tests

Mocking is one of the fundamental pillars of unit tests. It allows us to provide our tests with fake dependencies instead of using the actual ones. Mocks can emulate how a service might behave. For example:

  • It can return expected/unexpected data to the caller.
  • It can raise a business logic or network-related error.

Thus, it’s easy to test the correct behavior of every single facet of our program. Before moving on, let’s go over some good principles that we should follow while writing unit tests:

  • We should test the expected behavior instead of the concrete implementation of the dependencies. In practice, we care about what the code does, not about how the code does the job.
  • Unit tests only have to test a single independent unit of our software.
  • We don’t have to rely on external dependencies in our tests as they’re unstable and potentially slow.

Let’s introduce an example to highlight the ...