Testing problem

3 months ago by 1_4M_N008 to c/golang

I have a todo CLI app with the following structure

tree .
.
|-- cmd
|   `-- todo
|       |-- main.go
|       `-- main_test.go
|-- go.mod
|-- todo.go
|-- todo.json
`-- todo_test.go

In the main.go, I have a function called expand, it expand range string like in the cut command When I call the expand function from main_test.go, I get the following error

cmd/todo/main_test.go:141:12: undefined: expand
FAIL  PACKAGE_URI/todo/cmd/todo [build failed]
FAIL

I tried to change the function visibility, but this doesn't help either. I replicated the dir structure on a dummy project, and it did work!!

codeberg.org repo

edit: Add repo uri

karlhungus 2 points 3 months ago path: 0 24858691, hotness: undefined, score: 2, children: 5
1_4M_N008 1 point 3 months ago

same error

# URI/cmd/todo_test [URI/todo/cmd/todo.test]
cmd/todo/main_test.go:141:12: undefined: expand
ok      URI/todo 0.002s
FAIL    URI/todo/cmd/todo [build failed]
FAIL
path: 0 24858691 24859031, hotness: undefined, score: 1, children: 4
karlhungus 1 point 3 months ago

this might have some answers https://go-cloud-native.com/..., hard to verify without a repo, also recommend you post the commands you run when seeking help.

path: 0 24858691 24859031 24859460, hotness: undefined, score: 1, children: 3
1_4M_N008 1 point 3 months ago

thanks for your help, this is the repo on dev brach

path: 0 24858691 24859031 24859460 24866074, hotness: undefined, score: 1, children: 2
karlhungus 3 points 3 months ago

Your specific question is answered here: https://www.sobyte.net/....

Well, here’s the problem! This _testmain.go is the main package of the test executable generated by go test, and it now imports a “main” package, which is not allowed in Go.

Generally this is easily solved by moving the code you are testing to a package for example pkg/todo.go and pkg/todo_test.go or utility or whatever.

Finally if you look at that link i sent they recommend not testing main in exactly the way you are testing it. One negative of the way you are testing it is you aren't really unit testing -- every time you run main_test you compile main, this is a little unusual.

path: 0 24858691 24859031 24859460 24866074 24868561, hotness: undefined, score: 3, children: 1
bizdelnick 1 point 3 months ago
path: 0 24872257, hotness: undefined, score: 1, children: 0
Antergo 1 point 3 months ago

It is possible to give the test files access to the non-exported symbols by putting it also in package main

path: 0 24873096, hotness: undefined, score: 1, children: 0
golang
golang

@lemmy.ml

login for more options
1723
89
1

go to feed...