Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this function undefined when I run `go test`?

Tags:

go

Here is the code

a.go

package main

import "fmt"

func Haha() {
    fmt.Println("in Haha")
}

func main() {
}

a_test.go

package main_test

import "testing"

func TestA(t *testing.T) {
    Haha()
}

go build works. But when I run ~/gopath/src/zjk/misc$ go test -v. Here is what I get

# zjk/misc_test
./a_test.go:6: undefined: Haha
FAIL    zjk/misc [build failed]
like image 509
zjk Avatar asked Nov 16 '25 12:11

zjk


1 Answers

You need to import "main" in main_test package & call it like main.Haha().

Just to elaborate why one might have the tests for a package under a different package, I should say there are two categories of tests:

  • First, those tests that supervise the implementation of a package, the internals, to assure it's integrity, resource usage profile and performance benchmarks and the like. These tests should reside alongside the package code itself.
  • Second are those that test the functionality and usage of the package. In these tests, we want to assure a package stands up to it's claims about the service it provides. An important aspect of these tests is that they assure that we are not exposing any unnecessary details; to ensure private parts remain private and public API is crystal clear. That's why these tests should reside in another package, under a different name, to act as a consumer of the package under the test.

One exception is package main which is not meant to be used from inside other packages, so we just write all tests inside the package itself (as @kostya commented).

like image 86
Kaveh Shahbazian Avatar answered Nov 19 '25 10:11

Kaveh Shahbazian