unit-testinggotestinggo-modules

Are libraries for testing incorporated in final build


I'm wondering if the libraries that I use for tests only will be included in the final build distribution. I see dependencies in go.mod/go.sum files but I can't check final binary.

I guess that the Go build tool deals somehow with redundant code but I haven't found any pieces of evidence.

Could somebody point me to that spot in the documentation or describe behavior?


Solution

  • Official doc: Command go: Compile packages and dependencies:

    When compiling packages, build ignores files that end in '_test.go'.

    Also from package doc of testing:

    To write a new test suite, create a file whose name ends _test.go that contains the TestXxx functions as described here. Put the file in the same package as the one being tested. The file will be excluded from regular package builds but will be included when the “go test” command is run.

    Building your app doesn't even touch the test files. So no, dependencies only referred to from tests are not included in the executable binary.

    Also how hard is it to test? Write a simple app, build it. Note the size of the compiled binary.

    Add a test file, refer to some lib. Build again, the size won't change. Now if you refer to the package from the app and build again, it will grow.

    Example:

    package main
    
    func main() {
        println("Hello world")
    }
    

    Built on linux (Go 1.13), size is: 1,148,861 bytes.

    Adding a test:

    package main
    
    import (
        "fmt"
        "testing"
        "time"
    )
    
    func TestOne(t *testing.T) {
        fmt.Println(time.Now())
    }
    

    Size doesn't change. Now adding this TestOne() function (along with the required imports) to the main app: size increased to 2,165,259 bytes.