Home > Software design >  How to test library functions in Golang
How to test library functions in Golang

Time:01-14

I'm learning Go so I'm writing some basic utils and libraries for fun that I can reuse in other modules.

When importing them inside another module (using go get for example), I can use them just fine.

As I understand, Go will look for a package main and a main function to know the entrypoint when trying to run a go app/module.

The thing is that the libraries are not in "package main", not in main.go and have no main function, so how am I supposed to use the cli and use go run . to test the behavior of my function?

Do I absolutely need to create another module with a main.go file inside a package main? Or do I need to create a test file and use go test ?

Thank you!

CodePudding user response:

go test is the preferred way to test Go code.

If you do not want to use go test for some reason, then use build constraints and the go run command to execute a main program from the same directory as your package.

Here's an example program with a build constraint. Place the file in the same directory as the package source files. The comment //go:build ignore is a build constraint that excludes the file from the package sources.

//go:build ignore

package main

import (
    "your/package/import/path"  // <-- modify to your path
    "fmt"
)

func main() {
     // do something with your package here.
     fmt.Println("example")
}

Assuming that the above file is named program.go, run the program from the package directory with the command:

go run program.go

The go run command is OK for running toy or test programs like this. Prefer the go build command for anything else.

CodePudding user response:

Non-main packages (i.e., library packages) are not runnable.

To run the code in them, you must either run a main package that imports and runs their code, or write test functions in _test.go files to run the code. Note that test files are not just for unit tests; you can write whatever you want in them, and they can often be easier than creating a new main package for testing.

Modern IDEs now will allow you to easily run individual tests in debugging mode, so you can step through your code and see if it's working how you expect. If you prefer print debugging and doing everything from the command-line, you can still run an individual test and see the print output like this:

// something_test.go
package mylibrary

func TestSomeFunction(t *testing.T) {
    SomeFunction()
}
go test mylibrary -v -run TestSomeFunction
  •  Tags:  
  • go
  • Related