« Back to Index

Go test with interface

View original Gist on GitHub

_README.md

The purpose of this gist is to show you how to use an interface for swapping out behaviour within a testing context. This allows you to fake (i.e. mock) specific functionality so you don’t have to rely on actual network conditions for your unit tests.

I’ve used a custom interface here (e.g. FooIO), but in reality/practice you’d likely use a built-in interface.

For example, the Reader interface.

Or maybe a ReadWriter interface, which combines the Reader and Writer interfaces.

foo.go

package main

import "fmt"

type FooIO interface {
  Read() string
}

type Foo struct{}

func (f *Foo) Read() string {
  return "We READ something from disk"
}

func Stuff(f FooIO) string {
  return f.Read()
}

func main() {
  foo := &Foo{}
  contents := Stuff(foo)
  fmt.Println(contents)
}

foo_test.go

package main

import (
  "testing"

  "github.com/stretchr/testify/assert"
)

type FakeFoo struct{}

func (s *FakeFoo) Read() string {
  return "We 'pretend' to READ something from disk"
}

func TestSomething(t *testing.T) {
  assert := assert.New(t)

  foo := &FakeFoo{}
  contents := Stuff(foo)

  assert.Equal(contents, "We 'pretend' to READ something from disk")
}