无法访问同一程序包中的私有方法进行测试

时间:2019-12-03 05:47:00

标签: go testing

我在同一软件包中有2个文件。

# my_package1/my_file1.go

func myFunc1() {
  //....
} 

# my_package1/my_file1_test.go

type MyPackageSuite struct {
  suite.Suite
}

func (s *MyPackageSuite) MyTest1() {
  //...............

  res1 := myFunc1()

  //...............
} 

我运行测试go test my_package1/my_file1_test.go -v,它返回undefined: myFunc1

但是它们在同一个包中。为什么会出错?如何解决?公开该方法不是我想要的。

更新1

$ ls webhook
doc.go      webhook.go  webhook_test.go

然后

$ go test webhook
can't load package: package webhook: malformed module path "webhook": missing dot in first path element


$ go test webhook/webhook
can't load package: package webhook/webhook: malformed module path "webhook/webhook": missing dot in first path element

$ go test webhook/webhook.go
?     command-line-arguments  [no test files]


$ go test webhook/webhook_test.go 
# command-line-arguments [command-line-arguments.test]
webhook/webhook_test.go: undefined: myFunc1
FAIL  command-line-arguments [build failed]
FAIL

1 个答案:

答案 0 :(得分:1)

尝试go test ./my_package1强制编译all软件包。
或至少先go build

其目的是确保在执行测试文件之前已编译myFunc1()


malformed module path”“ missing dot in first path element”表示一个go mod file is missing

cd /path/to/project
go mod init project
go test ./webhook