使用公共构造函数对私有类型进行表驱动测试

huangapple go评论96阅读模式
英文:

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

是的,将其导出为Appgolang/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.

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

huangapple
  • 本文由 发表于 2021年10月21日 08:54:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/69654621.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定