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?
获取当前正在执行的测试的名称?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
dongliaojing0554 2016-02-21 21:13关注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.Tis defined as follows:type T struct { common name string // Name of test. startParallel chan bool // Parallel tests will wait on this. }So the struct
thas the name of the test in a field calledname. 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
reflectpackage to access the unexportednameand get the test name fromt: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
namefrom the testing package.本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报