3

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?

kcza
  • 63
  • 5

1 Answers1

4

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)
    }
}
mpx
  • 1,168
  • 1
  • 13
  • 2
    I'm afraid this doesn't work for me as I want `TestFoo` to be present in the example because I need to show people how to use my stuff within a Go unit test – kcza Feb 06 '23 at 14:42
  • Also, whilst I agree that the `testing` package shouldn't be used in deployed code, I don't think that the place where code will be used affects a user's need for examples – kcza Feb 06 '23 at 15:16
  • lol I love how much this doesn't even address the question. For a *testing* library, the production code **is** a test. That's the only place where it will run into! – marco6 Feb 06 '23 at 16:26
  • 2
    Oops, I missed this was for test frameworks. Updated to provide the best options available. – mpx Feb 06 '23 at 20:48