How to Use Testify for Assertions and Mocking in Go

Use Testify's assert package for readable checks and the mock package to simulate dependencies in Go tests.

Use the assert package for non-fatal checks and the mock package to simulate dependencies by embedding mock.Mock in your test structs.

package yours

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

// MyMockedObject embeds mock.Mock to enable mocking
type MyMockedObject struct {
	mock.Mock
}

// DoSomething implements the interface method
func (m *MyMockedObject) DoSomething(number int) (bool, error) {
	args := m.Called(number)
	return args.Bool(0), args.Error(1)
}

func TestSomething(t *testing.T) {
	// Setup mock
	testObj := new(MyMockedObject)
	testObj.On("DoSomething", 123).Return(true, nil)

	// Execute code using testObj
	// targetFuncThatDoesSomethingWithObj(testObj)

	// Assert expectations were met
	testObj.AssertExpectations(t)

	// Use assert for value checks
	assert.Equal(t, true, true, "values should be equal")
}