feat: initial project setup
This commit is contained in:
64
internal/handlers/book_handler_test.go
Normal file
64
internal/handlers/book_handler_test.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"git.workflows.cl/mcabezas/testing-go-example/internal/models"
|
||||
)
|
||||
|
||||
func TestGetBook(t *testing.T) {
|
||||
handler := NewBookHandler()
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/books/1", nil)
|
||||
|
||||
// Configurar contexto de chi con el parámetro id
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("id", "1")
|
||||
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetBook(w, req)
|
||||
|
||||
// Verificar código de estado
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("esperaba status 200, obtuvo %d", w.Code)
|
||||
}
|
||||
|
||||
// Verificar respuesta
|
||||
var book models.Book
|
||||
if err := json.NewDecoder(w.Body).Decode(&book); err != nil {
|
||||
t.Fatalf("error al decodificar: %v", err)
|
||||
}
|
||||
|
||||
if book.ID != "1" {
|
||||
t.Errorf("esperaba ID '1', obtuvo '%s'", book.ID)
|
||||
}
|
||||
|
||||
if book.Title != "El Quijote" {
|
||||
t.Errorf("esperaba título 'El Quijote', obtuvo '%s'", book.Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetBook_NotFound(t *testing.T) {
|
||||
handler := NewBookHandler()
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/books/999", nil)
|
||||
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("id", "999")
|
||||
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetBook(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("esperaba status 404, obtuvo %d", w.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user