Why does Go allow you to define `TestMain` without actually running the tests with `m.Run()`?

Hello!

The Go docs on testing make it clear that if you have a TestMain function defined in a file ending _test.go, you need to explicitly call m.Run() to actually run the unit tests in that package. Is there a reason there is no linting against you forgetting to actually call m.Run()?

It’s quite easy to forget to add this call. When this happens, the test runner makes it appear as though everything is passing for the package, when in actual fact the tests simply aren’t actually being run.

Is there a use-case where m.Run() might not be called? If not, is there a reason Go doesn’t have any sort of static check to ensure you do actually run the tests, if you’ve defined a TestMain function?

Thanks!

I think the answer lies here:

TestMain is a low-level primitive and should not be necessary for casual testing needs, where ordinary test functions suffice.

When using low-level primitives, more onus is on the developer to know what they are doing and do the right thing. I do think a linting rule would make sense, but, it probably hasn’t come up since the majority of projects aren’t using TestMain.

1 Like