英文:
Table driven tests for private types with public constructors
问题
我正在尝试减少我的API的表面积,所以我将我的app
结构体设为非导出(小写名称),只暴露了New
函数:
package mylib
type app struct {
}
func New() *app {
return &app{}
}
但是现在,我想为这个东西编写一个表驱动测试,但是我不能在结构体中持有mylib.app
:
package mylib_test
import (
"testing"
"mylib"
)
func TestApp(t *testing.T) {
tests := []struct {
name string
app private_type_public_new.app // 这部分不起作用
}{
// ...
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
}
我有哪些选择?我应该将app结构体设为公开(App
),并将所有字段设为非导出吗?我是否可以使用高阶函数来存储New
函数的实例,以在子测试中实例化应用程序?还有其他方法吗?
英文:
I'm trying to reduce the surface area of my API, so I made my app
struct non-exported (with the lowercase name), and only exposed the New
function:
package mylib
type app struct {
}
func New() *app {
return &app{}
}
But now, I want to write a table-driven test for this thing, and I can't hold a mylib.app
in a struct:
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) {
})
}
}
What options do I have? Should I make the app struct public (App
) and leave all the fields unexported? Is there something interesting I can do with higher order functions to store instances of the New
function to instantiate apps within the subtests? Something else?
答案1
得分: 0
是的,将其导出为App
。golang/lint
(现已弃用)特别警告导出的函数引用未导出的类型,因为这对于使用您的包的消费者来说很困难。例如,如果您分配了x := mylib.New()
,使得x
是*myapp.app
的实例,go-pls
将只显示该变量的类型,意味着您附加的任何描述性注释都不会显示。
请参阅https://github.com/golang/lint/issues/210
英文:
> What options do I have? Should I make the app struct public (App) and leave all the fields unexported?
Yes, export it as App
. golang/lint
(now deprecated) specifically warned about exported functions that referenced unexported types, as they are difficult for consumers of your package to work with. For example, if you assign x := mylib.New()
such that x
is an instance of *myapp.app
, go-pls
will show nothing about this variable except its type, meaning any descriptive comment you've attached to it will not appear.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论