hotmeatballsoup
hotmeatballsoup

Reputation: 625

Go test can access production functions but not test functions

I have a Go 1.14 project with the following directory structure:

myapp/
  server/
    payments/
      capture_payment.go
      capture_payment_test.go
  billing/
    billing.go
    billing_test.go
  fulfillment/
    fulfillment.go
    fulfillment_test.go

In my billing.go file I have:

package billing

import (
    "fmt"
)

func Flim() {
    fmt.Println("FLIM")
}

In my fulfillment_test.go file I have:

package fulfillment

import (
    "fmt"
)

func Flam() {
    fmt.Println("FLAM")
}

In my capture_payment_test.go file I have:

package payments

import (
  "testing"
  
  "github.com/myorg/myapp/billing"
  "github.com/myorg/myapp/fulfillment"
)

func TestSomething(t *testing.T) {
  billing.Flim()
  fulfillment.Flam()
}

When I cd into server/payments and run go test I get the following error:

$ go test
# github.com/myorg/myapp/server/payments [github.com/myorg/myapp/server/payment.test]
./capture_payment_test.go:12:2: undefined: fulfillment.Flam
FAIL    github.com/myorg/myapp/server/payments [build failed]

Can anyone spot why fulfillment.Flam() is undefined, but billing.Flim() is perfectly fine?

Upvotes: 0

Views: 76

Answers (1)

Marc
Marc

Reputation: 21055

This is explained in the overview of the testing package:

To write a new test suite, create a file whose name ends _test.go .... Put the file in the same package as the one being tested. The file will be excluded from regular package builds ...

This means that Flam() will not be part of the fulfillment package and cannot be used from other packages. If you want test utilities to be used by other packages, you need to put them in regular *.go files rather than *_test.go.

Upvotes: 4

Related Questions