Separating unit tests and integration tests in Go

前端 未结 4 1175
灰色年华
灰色年华 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:10

    I was trying to find a solution for the same recently. These were my criteria:

    • The solution must be universal
    • No separate package for integration tests
    • The separation should be complete (I should be able to run integration tests only)
    • No special naming convention for integration tests
    • It should work well without additional tooling

    The aforementioned solutions (custom flag, custom build tag, environment variables) did not really satisfy all the above criteria, so after a little digging and playing I came up with this solution:

    package main
    
    import (
        "flag"
        "regexp"
        "testing"
    )
    
    func TestIntegration(t *testing.T) {
        if m := flag.Lookup("test.run").Value.String(); m == "" || !regexp.MustCompile(m).MatchString(t.Name()) {
            t.Skip("skipping as execution was not requested explicitly using go test -run")
        }
    
        t.Parallel()
    
        t.Run("HelloWorld", testHelloWorld)
        t.Run("SayHello", testSayHello)
    }
    

    The implementation is straightforward and minimal. Although it requires a simple convention for tests, but it's less error prone. Further improvement could be exporting the code to a helper function.

    Usage

    Run integration tests only across all packages in a project:

    go test -v ./... -run ^TestIntegration$
    

    Run all tests (regular and integration):

    go test -v ./... -run .\*
    

    Run only regular tests:

    go test -v ./...
    

    This solution works well without tooling, but a Makefile or some aliases can make it easier to user. It can also be easily integrated into any IDE that supports running go tests.

    The full example can be found here: https://github.com/sagikazarmark/modern-go-application

提交回复
热议问题