获取当前正在执行的测试测试的名称?

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

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(&quot;Test name is %s&quot;, t.Name())
}

Here's the docs and here's the code.

答案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(&quot;name&quot;)

// name == &quot;TestSomething&quot;

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.

huangapple
  • 本文由 发表于 2016年2月21日 19:41:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/35535635.html
匿名

发表评论

匿名网友

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

确定