This project demonstrates how to write unit tests in Golang using the stretchr/testify
package. It simulates a simple blog-like structure with users and posts, and tests the application logic in isolation using mocks.
- Golang – The main programming language
- Echo – A fast, minimalistic web framework for building REST APIs
- GORM – An ORM library for Golang to interact with MySQL
- MySQL – The relational database used for persistent storage
- Testify – Provides easy-to-use assertion and mocking capabilities for unit tests
We use the github.com/stretchr/testify
package to write clean and expressive unit tests.
- Table-driven tests
- Mocking interfaces (e.g., repository methods)
- Assertions like
require.NoError()
,require.Len()
, etc.
func TestGetUserPosts(t *testing.T) {
mockRepo := new(mocks.PostRepoMock)
mockRepo.On("GetUserPosts", "test@example.com").Return([]models.Post{{Title: "Post 1"}}, nil)
posts, err := mockRepo.GetUserPosts("test@example.com")
require.NoError(t, err)
require.Len(t, posts, 1)
mockRepo.AssertExpectations(t)
}
Make sure dependencies are installed:
go mod tidy
go mod vendor
go test ./...
-
Create a database for the project
CREATE DATABASE GOLANG_UNIT_TESTS;
-
Update the
DSN
string for right user-name and password inconfigs/gorm.go
func InitDatabase() { db, err := gorm.Open(mysql.New(mysql.Config{ DSN: "root:shahil@tcp(127.0.0.1:3306)/GOLANG_UNIT_TESTS?charset=utf8&parseTime=True&loc=Local", }), &gorm.Config{}) if err != nil { panic("Error connecting to the Database") } err = db.AutoMigrate(&models.User{}, &models.Post{}) if err != nil { log.Fatal("Error auto migrating schemas", err) } DB = db }
go run .