What does "testing.T" mean in Golang?
Asked Answered
W

1

5

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.

Wien answered 17/7, 2022 at 1:54 Comment(2)
The Go compiler uses the methods from t *testing.T to determine the result of your test. In other languages you may have to write an assertion such as expect(true).toBe(true), whereas in Go, unless you use a third-party package, you just use regular if statements to assert something, and then call the methods from t to tell the compiler whether what you are testing has passed or has failed.Malignity
T is a poorly named type in the testing package, an instance of which serves as the interface to the test runtime. You mainly use it to inform the runtime of test failure through calls of t.Error() and such, which in turn then affects the exit status of the invocation of the go test command which started your test.Dermato
F
6

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.

Fastness answered 17/7, 2022 at 4:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.