Mock Functions in Golang

In Go, you can use interfaces and dependency injection to mock functions for testing purposes. By creating an interface that defines the functions you want to mock and injecting it as a dependency into the component you’re testing, you can easily swap out the real implementation with a mock implementation during testing.

In Go, “mocking” is a common technique used in unit testing to isolate the code under test and avoid executing external systems or functions.

The idea is to replace a real function or method with a fake version that behaves as you dictate for the purpose of testing. This can be particularly useful to avoid making real network calls, database access, file I/O, or any other external system interactions.

Let’s go through a step-by-step guide!

Step 1: Create a file named service.go with the following code.

package main

type Greeter interface {
  Greet(name string) string
}

type RealGreeter struct{}

func (rg RealGreeter) Greet(name string) string {
  return "Hello, " + name
}

func Welcome(g Greeter, name string) string {
  return g.Greet(name)
}

In this example, we defined a Greeter interface with a Greet() method and a RealGreeter struct that implements the interface. The Welcome() function takes a Greeter interface as a dependency.

Step 2: Create a file named service_test.go to the same directory

package main

import (
  "testing"
)

type MockGreeter struct{}

func (mg MockGreeter) Greet(name string) string {
  return "Mocked Greeting, " + name
}

func TestWelcome(t *testing.T) {
  mockGreeter := MockGreeter{}
  name := "Krunal"
  expected := "Mocked Greeting, " + name

  result := Welcome(mockGreeter, name)
  if result != expected {
    t.Errorf("Expected '%s', but got '%s'", expected, result)
  }
}

Go to the root of the project folder and execute the below command.

go test -v

Output

=== RUN TestWelcome
--- PASS: TestWelcome (0.00s)
PASS
ok _/Users/krunallathiya/Desktop/Code/ 0.301s

You can see that the test has passed.

If you encounter an error like this: go: go.mod file not found in current directory or any parent directory; see ‘go help modules’, then you can fix it by going to the terminal and executing the below command.

go env -w GO111MODULE=off

Now, the error will get fixed.

In this example, we have successfully mocked the Greet() function using an interface and dependency injection, making it easy to test the Welcome() function with a mocked implementation.

That’s it.