神刀安全网

Go: Subtests and Sub-benchmarks

Go: Subtests and Sub-benchmarks

Go uses a very simple approach to everything. This also includes the testing package that ships with Go. The lack of assertions often drives people to use another testing framework like testify .

Go 1.7 introduced subtest and sub-benchmarks. I haven’t seen much written on this yet… So here is a quick run down.

Subtests are exactly what they sound like, it’s running a test inside another test:

func TestFoo(t *testing.T) {     // <setup code>     t.Run("A=1", func(t *testing.T) { ... })     t.Run("A=2", func(t *testing.T) { ... })     t.Run("B=1", func(t *testing.T) { ... })     // <tear-down code> }

This is useful for grouping or sharing tests that need to use the same data fixtures.

Since each individual subtests get their own test name (as if it was independent) you can use this for filtering on the command line:

go test -run Foo     # Run top-level tests matching "Foo". go test -run Foo/A=  # Run subtests of Foo matching "A=". go test -run /A=1    # Run all subtests of a top-level test matching "A=1".

Parallel Tests

The existing testing package does have support for running tests in parallel, usually for benchmarks. However, I have not seen it used that much. Perhaps because it is difficult or messy to manage them.

Subtests greatly simplify by both locally grouping the tests and intrinsically running them in parallel and only moving on once all the subtests have finished:

func TestTeardownParallel(t *testing.T) {     // t.Run() will not return until the parallel tests finish.     t.Run("group", func(t *testing.T) {         t.Run("Test1", parallelTest1)         t.Run("Test2", parallelTest2)         t.Run("Test3", parallelTest3)     })     // <tear-down code> }

Thank you for reading. I’d really appreciate any and all feedback, please leave your comments below or consider subscribing. Happy coding.

Elliot Chance –

I’m a data nerd and TDD enthusiast living in Sydney, Australia. I love exploring new technologies and working on modern ways to solve age old problems.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Go: Subtests and Sub-benchmarks

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址