【问题标题】:Testing Unexported Functions in Go在 Go 中测试未导出的函数
【发布时间】:2019-04-23 07:08:34
【问题描述】:

我有一个名为example.go 的文件和另一个名为example_test.go 的测试文件,它们都在同一个包中。我想在example.go中测试一些未导出的函数

当我运行测试时,example_test.go 中未定义未导出的函数。我想知道在同一包中的测试文件中测试未导出函数的最佳约定是什么?

【问题讨论】:

  • 请显示minimal reproducible example。如果测试文件在同一个包中,那么它可以访问所有包级别的标识符。
  • 如果它们在同一个包中,所有函数和全局变量应该可以相互访问。你是如何运行你的测试的? go test ./... ?
  • 未导出的标识符只能从同一个包中访问,因此请在 example_test.go 中使用相同的包声明(白盒测试)。它还必须与example.go 位于同一文件夹中。更多详情见How can I allow one package access to another package's unexported data only when testing?
  • 你现在跑得怎么样?只需将目录更改为foo/bar/,然后运行go test
  • “当我运行测试时,未导出的函数是未定义的” 不,它们不是。你又犯了一个错误。

标签: unit-testing go private-methods


【解决方案1】:

这也适用于私有类型的私有成员函数。

例如。

abc.go如下

package main

type abc struct {
        A string
}

func (a *abc) privateFunc() {

}

abc_test.go如下

package main

import "testing"

func TestAbc(t *testing.T) {
        a := new(abc)
        a.privateFunc()
}

对此运行 go test 应该会给你一个完整的通过,没有任何错误。

linux-/bin/bash@~/trials/go$ go test -v
=== RUN   TestAbc
--- PASS: TestAbc (0.00s)
PASS
ok      _/home/george/trials/go        0.005s

【讨论】:

    【解决方案2】:

    如果您的文件确实在同一个包中,这应该不是问题。我可以毫无问题地运行以下测试。

    目录结构:

    ~/Source/src/scratch/JeffreyYong-Example$ tree .
    .
    ├── example.go
    └── example_test.go
    

    example.go:

    package example
    
    import "fmt"
    
    func unexportedFunc() {
        fmt.Println("this totally is a real function")
    }
    

    example_test.go

    package example
    
    import "testing"
    
    func TestUnimportedFunc(t *testing.T) {
        //some test conditions
        unexportedFunc()
    }
    

    测试命令:

    ~/Source/src/scratch/JeffreyYong-Example$ go test -v .

    输出:

    === RUN   TestUnimportedFunc
    this totally is a real function
    --- PASS: TestUnimportedFunc (0.00s)
    PASS
    ok      scratch/JeffreyYong-Example     0.001s
    

    【讨论】:

    • example_test 是一个不同的包。但仍然有效
    • 这是不正确的,这两个文件都声明它们在 example 包中。如果它们在不同的包中(比如说AB),包B 中的测试需要引用包A 中的函数,这是不可能的,因为包A 中的函数没有被导出——因为在原始帖子中。
    • 只是指出答案中未提及的常见错误。说 example_test 和 example 在所有方面都不是同一个包,意味着我们可以在一个目录中声明第二个包,事实并非如此。类似:“_test 包不是同一个包,单元测试不必包含在其中”将是有用的信息。
    【解决方案3】:

    正在运行go test /path/to/testfile_test.go 不会自动编译 /path/to/testfile.go 中的任何定义

    您可以改用go test /path/to/ 运行测试。

    【讨论】:

      猜你喜欢
      • 2011-07-06
      • 2015-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多