Reducing test bloat with table-driven tests

With table-driven tests, we define a slice of scenarios (often the function inputs, mock configuration, and our expectations) at the start of the test and then a scenario runner, which is typically part of the test that would otherwise have been duplicated. Let's see what this looks like as an example. The happy path test for the Load() function looks like this:

func TestLoad_happyPath(t *testing.T) {   expectedResult := &Person{      ID:       2,      FullName: "Paul",      Phone:    "0123456789",      Currency: "CAD",      Price:    23.45,   }   // define a mock db   testDb, dbMock, err := sqlmock.New()   require.NoError(t, err)   // configure the mock db   queryRegex := convertSQLToRegex(sqlLoadByID)   dbMock.ExpectQuery(queryRegex).WillReturnRows ...

Get Hands-On Dependency Injection in Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.