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.

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 (

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


=== RUN TestWelcome
--- PASS: TestWelcome (0.00s)
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.

Leave a Comment