GO · 테스트
인터페이스 기반 테스트
인터페이스를 이용하여 구현체를 교체 가능하게 만들고, 테스트에서 스텁/목을 주입합니다.
테스트중급interface-testfakeclockdeterministic
핵심 설명
인터페이스를 이용하여 구현체를 교체 가능하게 만들고, 테스트에서 스텁/목을 주입합니다.
Go code
package main
import (
"context"
"fmt"
"testing"
"time"
)
// 테스트 가능한 시간 인터페이스
type Clock interface {
Now() time.Time
}
type RealClock struct{}
func (c RealClock) Now() time.Time { return time.Now() }
type FakeClock struct{ Fixed time.Time }
func (c FakeClock) Now() time.Time { return c.Fixed }
// 테스트 가능한 서비스
type TokenService struct{ clock Clock }
func (s *TokenService) Generate() string {
t := s.clock.Now()
return fmt.Sprintf("token_%d", t.Unix())
}
func (s *TokenService) IsExpired(token string, maxAge time.Duration) bool {
// 토큰 생성 시각과 현재 시각 비교
return false // 간단한 예시
}
func TestTokenGeneration(t *testing.T) {
fixed := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
svc := &TokenService{clock: FakeClock{Fixed: fixed}}
token := svc.Generate()
expected := fmt.Sprintf("token_%d", fixed.Unix())
if token != expected {
t.Errorf("got %s, want %s", token, expected)
}
}
func main() {
_ = context.Background()
fmt.Println("인터페이스로 시간, 랜덤, IO를 테스트 가능하게")
}학습 팁
시간, 랜덤, 파일 시스템 등 비결정적 요소를 인터페이스로 추상화하면 테스트에서 예측 가능한 값을 주입할 수 있습니다.
주의할 점
time.Now()를 직접 호출하면 테스트가 시간에 의존하여 불안정해집니다. Clock 인터페이스를 주입하세요.
자주 묻는 질문
인터페이스 기반 테스트란 무엇인가요?
인터페이스를 이용하여 구현체를 교체 가능하게 만들고, 테스트에서 스텁/목을 주입합니다.
인터페이스 기반 테스트 학습 시 주의할 점은 무엇인가요?
time.Now() 를 직접 호출하면 테스트가 시간에 의존하여 불안정해집니다. Clock 인터페이스를 주입하세요.
Continue Learning
Go 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.