github.com/zoido/errassert

Simple table driven Go tests error assertions


Keywords
assert, assertions, go, golang, table-driven-test, test, testing, testing-tools
License
MIT
Install
go get github.com/zoido/errassert

Documentation

errassert: Simple table driven Go tests error assertions

go reference license CI coverage go report

Overview

  • set error assertion in a table driven test declaration
  • provides similar experience as Testify's ErrorAssertionFunc
  • define custom error assertions
  • combine assertions with errassert.Want
  • support assertions for gRPC status errors

Example

func Test(t *testing.T) {
	type testCase struct {
		in        string
		want      int
		errassert errassert.ErrorAssertion
	}

	run := func(t *testing.T, tc testCase) {
		_, err := strconv.Atoi(tc.in)

		tc.errassert.Require(t, err)
	}

	testCases := map[string]testCase{
		"ok": {
			in:        "42",
			want:      42,
			errassert: errassert.NilError(),
		},
		"invalid input fails": {
			in:        "invalid input",
			errassert: errassert.SomeError(),
		},
		"empty input cause invalid syntax error": {
			in:        "",
			// Common basic assertions.
			errassert: errassert.ErrorEndsWith("invalid syntax"),
		},
		"invalid input fails with input": {
			in: "input",
			// Combine basic assertions.
			errassert: errassert.Want(
				errassert.ErrorContains("\"input\""),
				errassert.ErrorEndsWith("invalid syntax"),
			),
		},
	}

	for name, tc := range testCases {
		t.Run(name, func(t *testing.T) { run(t, tc) })
	}
}

Credits

Based on experience within @h2oai.