skip to content
Alvin Lucillo

Assert expectations

/ 1 min read

If we add mock.AssertExpectations(t) to the testing I did in yesterday’s journal, it would fail:

FAIL: 0 out of 1 expectation(s) were met.
The code you are testing needs to make 1 more call(s).
for tn, tc := range tcs {
	t.Run(tn, func(t *testing.T) {
		var mock mockRepo
		tc.mockFn(&mock)
		// err := insertRec(&mock, tc.name)
		insertRec(&mock, tc.name)

		mock.AssertExpectations(t)

		// assert.Equal(t, tc.err, err)
	})
}

The error occurred because this test case sets an expectation that an insert call occurs. But actually there wasn’t any. Since the test case provides an empty name, the validation will return an error, thus the insert call will never happen.

This is the purpose of AssertExpectations. It ensures that whatever expectations we set are tested against the actual call.

// tc
"error validation": {
	name: "",
	err:  fmt.Errorf("invalid name value"),
	mockFn: func(m *mockRepo) {
		m.On("insert", "").Return(nil)
	},
},
// method to test
func insertRec(r repoQueryer, name string) error {

	if len(name) == 0 {
		return fmt.Errorf("invalid name value")
	}

	return r.insert(name)
}