Golang 中的“testing.T”是什么意思?

aad*_*yaa 4 testing interpreter go

当我在词法分析器的测试单元中遇到这一行时,我目前正在用Go 编写解释器:

package lexer 

import ( 

"testing"

"monkey/token"

)

func TestNextToken(t *testing.T) {
}
Run Code Online (Sandbox Code Playgroud)

“t *testing.T”的目的是什么?我知道它是指向测试库中某个字段的指针,但我不确定它在做什么。

稍后在代码中它是这样使用的:

for i, tt := range tests { 
     tok := l.NextToken()

     if tok.Type != tt.expectedType { 
          t.Fatalf("tests[%d] - tokentype wrong. expected=%q, got=%q", i, tt.expectedType, tok.Type) 
     }

     if tok.Literal != tt.expectedLiteral { 
           t.Fatalf("tests[%d] - literal wrong. expected=%q, got=%q", i, tt.expectedLiteral, tok.Literal) 
     }
}

Run Code Online (Sandbox Code Playgroud)

我通读了Golang 测试文档,但无法真正理解它的目的是什么或者为什么它被传递给测试函数。它只提到它是“传递给测试函数以管理测试状态并支持格式化测试日志的类型”,尽管我不确定如何在上述代码的上下文中解释它。

Sch*_*ern 6

func TestNextToken(t *testing.T)表示该函数采用指向测试包中类型 T 的指针。T 代表测试,F 代表模糊测试,B 代表基准测试等。该引用位于变量 中t

testing.T存储测试的状态。当 Go 调用您的测试函数时,它会将相同的内容传递testing.T给每个函数(大概)。你调用它的方法就像t.Fail说测试失败了,或者t.Skip说测试被跳过了等等。它会记住所有这些,Go 使用它来报告所有测试函数中发生的情况。