Search code examples
gotestinggodoc

How to write example tests in Go?


I'm writing a test framework and would like to put examples in my documentation. For maintainability, I'd like to have these examples tested but I can't figure out how.

Ideally, I would like a tested example which looks like:

func TestFoo(t *testing.T) {
    f := mytestframework.FromT(t)
    // code using f
}

Wrapping the above snippet in func ExampleFoo() { } doesn't work as function definitions can't be nested (this is a syntax error).

I've tried putting this in a separate example_test.go file, however godoc will mistake this for a test file, as according to the go.dev blog, on whole-file examples (emphasis my own):

A whole file example is a file that ends in _test.go and contains exactly one example function, no test or benchmark functions, and at least one other package-level declaration.

I've looked at the docs for Go's doc package, but I couldn't figure out whether this was useful to me.

I could just paste the example as a markdown code block into documentation somewhere, but then this wouldn't be tested and could quietly go out of date in future.

Is there any way to have example tests tested, or at least type-checked?


Solution

  • As designed, the testing package doesn't support executable examples using *testing.T. Currently by definition whole file examples must not include Test* functions.

    The best option is simply adding the example code as an indented block to the package or function documentation. This is how the testing package provides example documentation

    // Using test framework:
    //
    //      func TestFoo(t *testing.T) {
    //          framework(t)
    //      }
    

    Another option would be to use Example functions and declare the test function as an anonymous function

    func ExampleTesting() {
        _ = func(t *testing.T) {
            framework(t)
        }
    }