Skip to content

Instantly share code, notes, and snippets.

@ianfoo
Last active August 10, 2018 20:41
Show Gist options
  • Save ianfoo/b516bfedd71ee53a5cd6a36aef3ea1cc to your computer and use it in GitHub Desktop.
Save ianfoo/b516bfedd71ee53a5cd6a36aef3ea1cc to your computer and use it in GitHub Desktop.
golang: Separating Integration Tests and Unit Tests

Separating Integration Tests and Unit Tests

We can use build tags to run only certain types of tests. In this case, we want integration tests to run by default, so we tag the integration tests with a negated unit test tag, which indicates that the test should not be run if the unit build flag is set.

Alternatively, the integration tests could be tagged with integration or some other tag, and they'd only be run if the integration tag is set on test invocation.

How to run go test with tags

$ go test -tags unit
package foo
import "io"
type Foo struct{}
func (f Foo) String() string {
return "foo"
}
// Read is not properly implemented since it just returns EOF no matter what,
// even if the destination buffer is not large enough to contain the entire
// "foo" string, but for this example's purposes, it's fine. Do as I say, not
// as I do: don't actually write a reader like this. :O
func (f Foo) Read(b []byte) (int, error) {
s := []byte(f.String())
l := len(s)
if len(b) < l {
l = len(b)
}
return copy(b, s[:l]), io.EOF
}
// +build !unit
package foo
import (
"bytes"
"io"
"testing"
)
func TestRead(t *testing.T) {
f := Foo{}
w := &bytes.Buffer{}
io.Copy(w, f)
if w.String() != "foo" {
t.Error("expected 'foo'")
}
}
package foo
import "testing"
func TestFoo(t *testing.T) {
f := Foo{}
if f.String() != "foo" {
t.Error("expected 'foo'")
}
}
$ go test -v
=== RUN TestRead
--- PASS: TestRead (0.00s)
=== RUN TestFoo
--- PASS: TestFoo (0.00s)
PASS
ok _/tmp/test_test 0.006s
$ go test -v -tags unit
=== RUN TestFoo
--- PASS: TestFoo (0.00s)
PASS
ok _/tmp/test_test 0.006s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment