Home > Net >  What does "testing.T" mean in Golang?
What does "testing.T" mean in Golang?

Time:07-26

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.

CodePudding user response:

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.

  • Related