What does "testing.T" mean in Golang?

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

What does "testing.T" mean in Golang?

问题

package lexer

import (
    "testing"
    "monkey/token"
)

func TestNextToken(t *testing.T) {
}

在上述代码中,t *testing.T 是测试函数的参数。testing.T 是 Go 语言测试框架中的类型,它用于管理测试状态并支持格式化的测试日志。在测试函数中,我们可以使用 t 对象来记录测试结果、断言和错误信息。

在你提供的代码中,t 对象被用于记录测试失败时的错误信息。例如,在 for 循环中,我们使用 t.Fatalf 函数来记录测试失败的情况。如果 tok.Typett.expectedType 不相等,那么测试将失败,并且会打印出错误信息,其中包含了期望的类型和实际得到的类型。

总之,t *testing.T 参数的作用是支持测试框架的功能,包括记录测试结果、断言和错误信息。

英文:

I'm currently going through Writing an Interpreter in Go when I came across this line in the testing unit for the lexer:

package lexer 

import ( 

"testing"

"monkey/token"

)

func TestNextToken(t *testing.T) {
}

What is the purpose of "t *testing.T"? I understand that its a pointer to some field in the testing library, but I'm not sure what it's doing.

Later in the code it's used this way:

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) 
     }
}

I read through the Golang testing docs, but couldn't really understand what the purpose of it was or why it's being passed to the testing function. All it mentions is that it is a "type passed to Test functions to manage test state and support formatted test logs," though I'm not sure how to interpret that in the context of the above code.

答案1

得分: 4

func TestNextToken(t *testing.T) 表示该函数接受一个指向 testing 包中的类型 T 的指针。T 用于测试,F 用于模糊测试,B 用于基准测试等。该引用存储在变量 t 中。

testing.T 存储测试的状态。当 Go 调用你的测试函数时,它会向每个函数传递相同的 testing.T(假设如此)。你可以调用它的方法,比如 t.Fail 表示测试失败,或者 t.Skip 表示测试被跳过等。它会记住所有这些信息,Go 使用它来报告所有测试函数中发生的情况。

英文:

func TestNextToken(t *testing.T) says the function takes a pointer to the the type T in the testing package. T for tests, F for fuzzing, B for benchmarking, etc. That reference is in the variable t.

testing.T stores the state of the test. When Go calls your test functions, it passes in the same testing.T to each function (presumably). You call methods on it like t.Fail to say the test failed, or t.Skip to say the test was skipped, etc. It remembers all this, and Go uses it to report what happened in all the test functions.

huangapple
  • 本文由 发表于 2022年7月17日 09:54:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73008770.html
匿名

发表评论

匿名网友

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

确定