GO · 테스트
testify & Mock 테스트
외부 라이브러리 testify로 더 읽기 쉬운 테스트를 작성합니다.
테스트중급testifyassertrequiremockMockUserRepo
핵심 설명
외부 라이브러리 testify로 더 읽기 쉬운 테스트를 작성합니다.
Go code
// go get github.com/stretchr/testify
package main
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/mock"
)
// 인터페이스 정의
type UserRepo interface {
FindByID(id int) (*User, error)
Save(u *User) error
}
// Mock 구현
type MockUserRepo struct {
mock.Mock
}
func (m *MockUserRepo) FindByID(id int) (*User, error) {
args := m.Called(id)
return args.Get(0).(*User), args.Error(1)
}
func (m *MockUserRepo) Save(u *User) error {
return m.Called(u).Error(0)
}
// 서비스
type UserService struct{ repo UserRepo }
func (s *UserService) GetUser(id int) (*User, error) {
return s.repo.FindByID(id)
}
// 테스트
func TestGetUser(t *testing.T) {
mockRepo := new(MockUserRepo)
expected := &User{ID: 1, Name: "Alice"}
// Mock 설정
mockRepo.On("FindByID", 1).Return(expected, nil)
svc := &UserService{repo: mockRepo}
user, err := svc.GetUser(1)
// assert — 실패해도 계속
assert.NoError(t, err)
assert.Equal(t, expected.Name, user.Name)
assert.NotNil(t, user)
// require — 실패 시 즉시 중단
require.NotNil(t, user)
// Mock 호출 검증
mockRepo.AssertExpectations(t)
mockRepo.AssertCalled(t, "FindByID", 1)
}학습 팁
require는 테스트를 즉시 종료합니다. nil 포인터 역참조처럼 이후 로직이 안전하지 않을 때 사용하세요.
주의할 점
assert.Equal(t, expected, actual)에서 순서가 중요합니다: 첫 번째가 expected, 두 번째가 actual입니다. 반대로 쓰면 에러 메시지가 혼란스러워집니다.
자주 묻는 질문
testify & Mock 테스트란 무엇인가요?
외부 라이브러리 testify 로 더 읽기 쉬운 테스트를 작성합니다.
testify & Mock 테스트 학습 시 주의할 점은 무엇인가요?
assert.Equal(t, expected, actual) 에서 순서가 중요합니다: 첫 번째가 expected, 두 번째가 actual입니다. 반대로 쓰면 에러 메시지가 혼란스러워집니다.
Continue Learning
Go 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.