Junior
How did you work with testing in Go? Did you work with mocks?
sobes.tech AI
Answer from AI
In Go, the standard testing package is usually used for testing. Tests are written in files with the suffix _test.go and run with the command go test.
To mock dependencies, interfaces can be used and custom implementations created for tests. Additionally, third-party libraries like gomock or testify/mock are popular.
Here's an example of a simple test with a mock object:
package service
import (
"testing"
)
type UserRepository interface {
GetUser(id int) (User, error)
}
type User struct {
ID int
Name string
}
type UserService struct {
repo UserRepository
}
func (s *UserService) GetUserName(id int) (string, error) {
user, err := s.repo.GetUser(id)
if err != nil {
return "", err
}
return user.Name, nil
}
// Mock implementation of UserRepository
type MockUserRepo struct{}
func (m *MockUserRepo) GetUser(id int) (User, error) {
return User{ID: id, Name: "Test User"}, nil
}
func TestGetUserName(t *testing.T) {
mockRepo := &MockUserRepo{}
service := UserService{repo: mockRepo}
name, err := service.GetUserName(1)
if err != nil {
t.Fatal(err)
}
if name != "Test User" {
t.Errorf("expected 'Test User', got %s", name)
}
}
This approach allows isolating the code under test from real dependencies.