I am doing unit tests on Go
and according to some examples a test function is defined like this:
func TestAlgo(t *testing.T) {
...
}
What I want to know is what exactly does the parameter of that function mean?
I've also seen them do something like:
func TestAlgo(*testing.B) {
...
}
What is the difference with the previous parameter?
As you mentioned, all methods that you want to run as tests must be declared like this:
Why? it's simply a contract between you, the programmer, and the language, so that when you run the
go test
Go command, you run the unit tests unitarily. To recognize what they are, they must be implemented in methods of the formwhere each method starts with the word Test and Xxx is any alphanumeric string starting with an uppercase. In addition to this, the method must receive a variable of type as an argument
*testing.T
. Now, what does this parameter mean? To this method you are passing a pointer to a called structureT
that is inside the packagetesting
. This parameter is passed to all the methods that execute unit tests since the structure stores information about the state of the tests and the format in which it should print the logs if desired during the execution of the test. Here you can see the source code in which this structure is declared.The difference between
Y
is that the second method won't actually run as an automatic unit test, because it doesn't honor the contract that Go requires because it receives a pointer to a type structure
B
inside the packagetesting
. This structureB
references a data type that is used to run any benchmark, or performance, tests that you want to include. However, the correct declaration for methods that want to be executed like this is:Now, if you actually refer to the difference between
Y
(both with parameter pointing to a type structure
T
in the packagetesting
) is that there is really no difference. In Go, the variable name in function arguments is not strictly necessary, just the type. However, if you want to do something like:you will need to use the variable name to call the methods available in T to print errors, so you will need to declare the variable name as well, which is normally named by the reference
t
:There is more information about this in the Go documentation .