After my last email, discussing context.TODO()
, I got this question from Bruno Schaatsbergen:
Thanks for the blog Jonathan, as always a pleasure to read.
Regarding the last part on testing, any particular reason why you do not recommend using the new T.Context and B.Context methods?
Great question!
Go 1.24 added new methods to the testing package: T.Context
, B.Context
, and F.Context
. These methods return a context which is canceled when the test, benchmark, or fuzz test, respectively, is canceled. (For brevity, I’ll refer only to T.Context
from this point, to refer to any of these methods.)
So the question is: Why don’t I recommend using these methods?
The short answer to that is: I forgot!
The longer answer is: I should have mentioned it since I talked about testing, but I had intended to cover this topic a bit later in this series, after going over some additional background. But since the question came up, I’ll tackle it now.
So should you use the testing package’s Context
methods? In general, yes!
But there are occasional exceptions.
For most normal tests, T.Context()
is perfectly appropriate to use. But if you’re ever doing anything that is not scoped to a single test, that would be the time not to use it. This would typically apply to things like starting a test server, or a Docker container via Testcontainers or similar, which will be used for multiple tests. You don’t want to shut that down as soon sa the first test completes.