How to test the main package functions in golang?

ThePiachu picture ThePiachu · Jul 11, 2015 · Viewed 37.5k times · Source

I want to test a few functions that are included in my main package, but my tests don't appear to be able to access those functions.

My sample main.go file looks like:

package main

import (
    "log"
)

func main() {
    log.Printf(foo())
}

func foo() string {
    return "Foo"
}

and my main_test.go file looks like:

package main

import (
    "testing"
)

func Foo(t testing.T) {
    t.Error(foo())
}

when I run go test main_test.go I get

# command-line-arguments
.\main_test.go:8: undefined: foo
FAIL    command-line-arguments [build failed]

As I understand, even if I moved the test file elsewhere and tried importing from the main.go file, I couldn't import it, since it's package main.

What is the correct way of structuring such tests? Should I just remove everything from the main package asides a simple main function to run everything and then test the functions in their own package, or is there a way for me to call those functions from the main file during testing?

Answer

David Budworth picture David Budworth · Jul 11, 2015

when you specify files on the command line, you have to specify all of them

Here's my run:

$ ls
main.go     main_test.go
$ go test *.go
ok      command-line-arguments  0.003s

note, in my version, I ran with both main.go and main_test.go on the command line

Also, your _test file is not quite right, you need your test function to be called TestXXX and take a pointer to testing.T

Here's the modified verison:

package main

import (
    "testing"
)

func TestFoo(t *testing.T) {
    t.Error(foo())
}

and the modified output:

$ go test *.go
--- FAIL: TestFoo (0.00s)
    main_test.go:8: Foo
FAIL
FAIL    command-line-arguments  0.003s