英文:
Get the name of the currently executing testing test?
问题
在Go语言中,如何获取当前正在执行的测试的名称,即以Test开头的函数名称,而无需手动传递它?
英文:
In Go, how would I get the name of the currently executing test, the function name starting with Test, of the current test without passing it in manually?
答案1
得分: 23
只需使用Name()方法:
<!-- language: go -->
func TestSomethingReallyCool(t *testing.T) {
	t.Logf("测试名称为%s", t.Name())
}
英文:
Just use the Name() method:
<!-- language: go -->
func TestSomethingReallyCool(t *testing.T) {
	t.Logf("Test name is %s", t.Name())
}
答案2
得分: 4
这是一个有趣的问题。当你定义一个测试时,你会传递一个表示测试本身的结构体:
func TestSomething(t *testing.T) {
testing.T 被定义如下:
type T struct {
    common
    name          string    // 测试的名称。
    startParallel chan bool // 并行测试将等待此通道。
}
所以结构体 t 有一个名为 name 的字段来表示测试的名称。然而,由于某种原因,这个名称没有被导出,并且没有公共的访问器可以返回它。因此,你不能直接访问它。
有一个解决方法。你可以使用 reflect 包来访问未导出的 name 字段,并从 t 中获取测试的名称:
v := reflect.ValueOf(*t)
name := v.FieldByName("name")
// name == "TestSomething"
我不确定这是否是最佳的方法,但我没有找到其他合理的解决方案来从 testing 包中访问 name。
英文:
This is an interesting question. When you define a test, you pass around a struct that represents the test itself:
func TestSomething(t *testing.T) {
testing.T is defined as follows:
type T struct {
	common
	name          string    // Name of test.
	startParallel chan bool // Parallel tests will wait on this.
}
So the struct t has the name of the test in a field called name. However, for some reason, the name is not exported and there is no public accessor that will return it. Therefore, you can't access it directly.
There is a workaround. You can use the reflect package to access the unexported name and get the test name from t:
v := reflect.ValueOf(*t)
name := v.FieldByName("name")
// name == "TestSomething"
I'm not sure if this is the best approach, but I was not able to find another reasonable solution to access name from the testing package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论