Table 使用 public 构造函数对私有类型进行驱动测试

Table driven tests for private types with public constructors

我试图减少我的 API 的表面积,所以我让我的 app 结构不导出(使用小写名称),并且只暴露 New 函数:

package mylib

type app struct {
}

func New() *app {
    return &app{}
}

但是现在,我想为这个东西写一个table驱动的测试,我不能在结构中持有一个mylib.app:

package mylib_test

import (
    "testing"
    "mylib"
)

func TestApp(t *testing.T) {
    tests := []struct {
        name string
        app  private_type_public_new.app // This part doesn't work

    }{
        // ...
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {

        })
    }
}

我有什么选择?我应该使应用程序结构 public (App) 并保留所有字段未导出吗?我可以用高阶函数做一些有趣的事情来存储 New 函数的实例以在子测试中实例化应用程序吗?还有别的吗?

What options do I have? Should I make the app struct public (App) and leave all the fields unexported?

是的,将其导出为 Appgolang/lint(现已弃用)特别警告引用未导出类型的导出函数,因为您的包的使用者很难使用它们。例如,如果您分配 x := mylib.New() 使得 x*myapp.app 的一个实例,则 go-pls 将不显示此变量的任何信息,除了它的类型,这意味着您已经添加的任何描述性注释附加到它不会出现。

https://github.com/golang/lint/issues/210