Help working with testing

I wrote the below simple code, in order to try test in go:

package main

// Init is the input number, to be used as struct insted of directly calling
// the functions for simplicity purposes
type Init struct {
	Number int
}

func main() {
	d := Init{Number: 3}
	d.Double()
	println(d.Number, "(which is 3 by 2)")
}

// Double function retuning the input value multiplied by 2
func (d *Init) Double() {
	d.Number = d.Number * 2
}

func ExampleDouble() {
	// Create new buffer for the image
	d := Init{Number: 3}
	d.Double()
	println(d.Number, "(which is 3 by 2)")
	// Output:
	// 6 (which is 3 by 2)
}

And the double_test.go file is:

package main

import "testing"

func TestDouble(t *testing.T) {
	d := Init{Number: 3}
	d.Double()
	want := 6
	if got := d.Number; got != want {
		println("test failed")
	} else {
		println("test passed")
	}
}

While running:

go test -v double_test.go

I got the below error:

# command-line-arguments [command-line-arguments.test]
.\double_test.go:6:7: undefined: Init
FAIL    command-line-arguments [build failed]
FAIL

What is wrong here, should not the test file read the Init type as it is capitalized?

1 Like

Hi,
I am very beginner so sorry if the info is incorrect, butif you run the go commands like this, only the targeted file file will run, so now the double.go file content will not be visible for the compile process. Try without targeting the file so i think go test -v will work.

2 Likes

The main package is not importable, not is it automatically joined with files from the same folder. Use a different name for the package that main.

Thanks a lot, this worked very fine, wish you great journey with GO, Iā€™m new to it as well.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.