如何在Go中编写示例测试?

huangapple go评论84阅读模式
英文:

How to write example tests in Go?

问题

我正在编写一个测试框架,并希望在文档中添加示例。为了可维护性,我希望对这些示例进行测试,但我无法弄清楚如何做到。

理想情况下,我希望有一个经过测试的示例,看起来像这样:

func TestFoo(t *testing.T) {
    f := mytestframework.FromT(t)
    // 使用 f 的代码
}

将上面的代码片段包装在 func ExampleFoo() { } 中是行不通的,因为函数定义不能嵌套(这是语法错误)。

我尝试将其放在一个单独的 example_test.go 文件中,但是 godoc 会将其误认为是一个测试文件,根据 go.dev 博客上的说明(强调是我自己的):

整个文件示例是以 _test.go 结尾的文件,其中包含一个示例函数,没有测试或基准函数,以及至少一个其他的包级声明。

我查看了 Go 的 doc 包文档,但我无法确定它对我是否有用。

我可以将示例作为 Markdown 代码块粘贴到文档的某个地方,但这样就无法进行测试,而且在将来可能会悄悄过时。

有没有办法对示例进行测试,或者至少进行类型检查?

英文:

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?

答案1

得分: 4

根据设计,testing 包不支持使用 *testing.T 的可执行示例。目前,根据定义,整个文件示例不能包含 Test* 函数。

最佳选择是将示例代码作为缩进块添加到包或函数文档中。这就是 testing 包提供示例文档的方式

// 使用测试框架:
//
//      func TestFoo(t *testing.T) {
//          framework(t)
//      }

另一种选择是使用 Example 函数,并将测试函数声明为匿名函数

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

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)
    }
}

huangapple
  • 本文由 发表于 2023年2月6日 21:29:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361929.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定