Skip to content

Commit

Permalink
Add unit test for CreateLobby handler to verify successful lobby crea…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
justinfarrelldev committed Nov 23, 2024
1 parent 0e97e43 commit 32672b2
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions internal/lobby/create_lobby_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,46 @@ import (
"github.com/jmoiron/sqlx"
)

func TestCreateLobby_Success(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()

lobby := Lobby{
Name: "Test Lobby",
OwnerName: "Owner",
IsClosed: false,
IsMuted: false,
IsPublic: true,
}

mock.ExpectQuery("INSERT INTO lobby \\(name, owner_name, is_closed, is_muted, is_public\\) VALUES \\(\\$1, \\$2, \\$3, \\$4, \\$5\\)").
WithArgs(lobby.Name, lobby.OwnerName, lobby.IsClosed, lobby.IsMuted, lobby.IsPublic).
WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))

req, err := http.NewRequest("POST", "/lobby/create_lobby", strings.NewReader(`{"lobby": {"name": "Test Lobby", "owner_name": "Owner", "is_closed": false, "is_muted": false, "is_public": true}, "password": "password123"}`))
if err != nil {
t.Fatal(err)
}

rr := httptest.NewRecorder()
sqlxDB := sqlx.NewDb(db, "sqlmock")
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := CreateLobby(w, r, sqlxDB)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})

handler.ServeHTTP(rr, req)

if status := rr.Code; status != http.StatusCreated {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusCreated)
}
}

func TestCreateLobby_InvalidMethod(t *testing.T) {
db, _, err := sqlmock.New()
if err != nil {
Expand Down

0 comments on commit 32672b2

Please sign in to comment.