Separating unit tests and integration tests in Go

前端 未结 4 1209
灰色年华
灰色年华 2020-12-07 08:04

Is there an established best practice for separating unit tests and integration tests in GoLang (testify)? I have a mix of unit tests (which do not rely on any external reso

4条回答
  •  青春惊慌失措
    2020-12-07 08:11

    @Ainar-G suggests several great patterns to separate tests.

    This set of Go practices from SoundCloud recommends using build tags (described in the "Build Constraints" section of the build package) to select which tests to run:

    Write an integration_test.go, and give it a build tag of integration. Define (global) flags for things like service addresses and connect strings, and use them in your tests.

    // +build integration
    
    var fooAddr = flag.String(...)
    
    func TestToo(t *testing.T) {
        f, err := foo.Connect(*fooAddr)
        // ...
    }
    

    go test takes build tags just like go build, so you can call go test -tags=integration. It also synthesizes a package main which calls flag.Parse, so any flags declared and visible will be processed and available to your tests.

    As a similar option, you could also have integration tests run by default by using a build condition // +build !unit, and then disable them on demand by running go test -tags=unit.

    @adamc comments:

    For anyone else attempting to use build tags, it's important that the // +build test comment is the first line in your file, and that you include a blank line after the comment, otherwise the -tags command will ignore the directive.

    Also, the tag used in the build comment cannot have a dash, although underscores are allowed. For example, // +build unit-tests will not work, whereas // +build unit_tests will.

提交回复
热议问题