Skip to content

Mocking with Interfaces

Learn to create mock implementations for testing code with external dependencies.

Mocking allows you to test code in isolation by replacing real dependencies (like email services, databases, or APIs) with fake implementations. In Go, this is accomplished through interfaces and dependency injection.

A mock tracks how it’s called (arguments, call count) so you can verify your code interacts with dependencies correctly. Mocks can also simulate different scenarios like errors without needing real infrastructure.

Implement a user registration service that sends welcome emails, and test it using mocks:

  1. Create a MockEmailSender that tracks calls and can simulate errors
  2. Test UserService.RegisterUser using the mock
  3. Verify the mock receives correct arguments
  4. Test both success and error scenarios

Interface-Based Mocking

~20 minmedium

Create mocks to test a service with external dependencies

  • Interface-Based Mocking: Use interfaces to allow test doubles
  • Dependency Injection: Pass dependencies through constructors for testability
  • Test Doubles: Mocks track calls and can simulate different behaviors
  • Verification: Assert that dependencies are called with correct arguments
  • Error Simulation: Mocks can return errors without needing real failures