0

I have a main.go and main_test.go, and go test works fine:

$ cat main.go
package main

func main() {}

func F() int { return 1 }

$ cat main_test.go
package main

import "testing"

func TestF(t *testing.T) {
    if F() != 1 {
        t.Fatalf("error")
    }
}

From link1 and link2, I could use package main_test in main_test.go. But go test shows ./main_test.go:6:5: undefined: F. How to fix the error?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user2847598
  • 1,247
  • 1
  • 14
  • 25

1 Answers1

1

Import the main package. Use the following code assuming that the package path is "example.com/example".

$ cat main_test.go
package main

import (
     "testing"
     "example.com/example"   // import main
)

func TestF(t *testing.T) {
    if main.F() != 1 {      // use package selector when referring to F
        t.Fatalf("error")
    }
}

Replace example.com/example with the actual path of your package.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242