PHpullh
학습 라이브러리/Go/httptest 패키지

GO · 테스트

httptest 패키지

net/http/httptest로 HTTP 핸들러를 단위 테스트합니다. 실제 서버 없이 요청/응답을 테스트합니다.

테스트중급httptesthandler-testintegrationtesting

핵심 설명

net/http/httptest로 HTTP 핸들러를 단위 테스트합니다. 실제 서버 없이 요청/응답을 테스트합니다.

Go code

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}

func TestHealthHandler(t *testing.T) {
	req := httptest.NewRequest("GET", "/health", nil)
	rec := httptest.NewRecorder()

	healthHandler(rec, req)

	if rec.Code != 200 {
		t.Errorf("상태 코드: got %d, want 200", rec.Code)
	}

	var resp map[string]string
	json.Unmarshal(rec.Body.Bytes(), &resp)
	if resp["status"] != "ok" {
		t.Errorf("상태: got %s, want ok", resp["status"])
	}
}

// 테스트 서버로 통합 테스트
func TestWithServer(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(healthHandler))
	defer srv.Close()

	resp, err := http.Get(srv.URL + "/health")
	if err != nil { t.Fatal(err) }
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		t.Errorf("상태: %d", resp.StatusCode)
	}
}

func main() {
	fmt.Println("httptest: 핸들러 단위 테스트 & 서버 통합 테스트")
}

학습 팁

httptest.NewRecorder()는 핸들러 단위 테스트, httptest.NewServer()는 전체 HTTP 스택 통합 테스트에 사용합니다.

주의할 점

httptest.NewServer를 사용 후 defer srv.Close()를 빼먹으면 테스트 후 서버가 종료되지 않습니다.

자주 묻는 질문

httptest 패키지란 무엇인가요?

net/http/httptest 로 HTTP 핸들러를 단위 테스트합니다. 실제 서버 없이 요청/응답을 테스트합니다.

httptest 패키지 학습 시 주의할 점은 무엇인가요?

httptest.NewServer 를 사용 후 defer srv.Close() 를 빼먹으면 테스트 후 서버가 종료되지 않습니다.

Continue Learning

Go 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.