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.
t *testing.T
to determine the result of your test. In other languages you may have to write an assertion such asexpect(true).toBe(true)
, whereas in Go, unless you use a third-party package, you just use regularif
statements to assert something, and then call the methods fromt
to tell the compiler whether what you are testing has passed or has failed. – MalignityT
is a poorly named type in thetesting
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 oft.Error()
and such, which in turn then affects the exit status of the invocation of thego test
command which started your test. – Dermato