Back to / x / subtest

Package subtest

Latest Go to latest
Published: Nov 11, 2018 | License: Apache-2.0 | Module:


Package subtest provides a TestContext to subtests which handles cleanup, and provides a testing.TB, and context.Context.

This package was inspired by



Package Files

func Run

func Run(t *testing.T, name string, subtest func(t TestContext)) bool

Run a subtest. When subtest exits, every cleanup function added with TestContext.AddCleanup will be run.

Example (TableTest)


var testcases = []struct {
	data     io.Reader
	expected int
		data:     strings.NewReader("invalid input"),
		expected: 400,
		data:     strings.NewReader("valid input"),
		expected: 200,

for _, tc := range testcases {
	subtest.Run(t, "test-service-call", func(t subtest.TestContext) {

		url := startFakeService(t)

		req, err := http.NewRequest("POST", url,
		assert.NilError(t, err)
		req = req.WithContext(t.Ctx())

		client := newClient(t)
		resp, err := client.Do(req)
		assert.NilError(t, err)
		assert.Equal(t, resp.StatusCode, tc.expected)
Example (TestSuite)


subtest.Run(t, "test-one", func(t subtest.TestContext) {
	assert.Equal(t, 1, 1)
subtest.Run(t, "test-two", func(t subtest.TestContext) {
	assert.Equal(t, 2, 2)

type TestContext

type TestContext interface {
	// AddCleanup function which will be run when before Run returns.
	AddCleanup(f func())
	// Ctx returns a context for the test case. Multiple calls from the same subtest
	// will return the same context. The context is cancelled when Run
	// returns.
	Ctx() context.Context
	// Parallel calls t.Parallel on the testing.TB. Panics if testing.TB does
	// not implement Parallel.

TestContext provides a testing.TB and a context.Context for a test case.

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier