Separating unit tests and integration tests in Go

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

    To elaborate on my comment to @Ainar-G's excellent answer, over the past year I have been using the combination of -short with Integration naming convention to achieve the best of both worlds.

    Unit and Integration tests harmony, in the same file

    Build flags previously forced me to have multiple files (services_test.go, services_integration_test.go, etc).

    Instead, take this example below where the first two are unit tests and I have an integration test at the end:

    package services
    
    import "testing"
    
    func TestServiceFunc(t *testing.T) {
        t.Parallel()
        ...
    }
    
    func TestInvalidServiceFunc3(t *testing.T) {
        t.Parallel()
        ...
    }
    
    func TestPostgresVersionIntegration(t *testing.T) {
        if testing.Short() {
            t.Skip("skipping integration test")
        }
        ...
    }
    

    Notice the last test has the convention of:

    1. using Integration in the test name.
    2. checking if running under -short flag directive.

    Basically, the spec goes: "write all tests normally. if it is a long-running tests, or an integration test, follow this naming convention and check for -short to be nice to your peers."

    Run only Unit tests:

    go test -v -short
    

    this provides you with a nice set of messages like:

    === RUN   TestPostgresVersionIntegration
    --- SKIP: TestPostgresVersionIntegration (0.00s)
            service_test.go:138: skipping integration test
    

    Run Integration Tests only:

    go test -run Integration
    

    This runs only the integration tests. Useful for smoke testing canaries in production.

    Obviously the downside to this approach is if anyone runs go test, without the -short flag, it will default to run all tests - unit and integration tests.

    In reality, if your project is large enough to have unit and integration tests, then you most likely are using a Makefile where you can have simple directives to use go test -short in it. Or, just put it in your README.md file and call it the day.

提交回复
热议问题