Skip to content

Instantly share code, notes, and snippets.

@BK1031
Created July 16, 2024 18:02
Show Gist options
  • Save BK1031/0dced9cffa10ebe7d78cf4c5dd252096 to your computer and use it in GitHub Desktop.
Save BK1031/0dced9cffa10ebe7d78cf4c5dd252096 to your computer and use it in GitHub Desktop.
singlestore-go-bookstore testcreatebook api
func TestCreateBook(t *testing.T) {
// Arrange
book := model.Book{
Title: "The Great Gatsby",
Author: "F. Scott Fitzgerald",
Price: 29.99,
Genre: "Fiction",
}
reqBody, _ := json.Marshal(book)
t.Run("Success", func(t *testing.T) {
// Act
req := httptest.NewRequest("POST", "/books", bytes.NewBuffer(reqBody))
w := httptest.NewRecorder()
Router.ServeHTTP(w, req)
// Assert
if w.Code != http.StatusCreated {
t.Errorf("Expected status code %d, got %d", http.StatusCreated, w.Code)
}
})
t.Run("Invalid Book", func(t *testing.T) {
// Arrange
invalidBook := model.Book{
ID: 1,
}
reqBody, _ := json.Marshal(invalidBook)
// Act
req := httptest.NewRequest("POST", "/books", bytes.NewBuffer(reqBody))
w := httptest.NewRecorder()
Router.ServeHTTP(w, req)
// Assert
if w.Code != http.StatusInternalServerError {
t.Errorf("Expected status code %d, got %d", http.StatusInternalServerError, w.Code)
}
})
t.Run("Invalid Request", func(t *testing.T) {
// Act
req := httptest.NewRequest("POST", "/books", nil)
w := httptest.NewRecorder()
Router.ServeHTTP(w, req)
// Assert
if w.Code != http.StatusBadRequest {
t.Errorf("Expected status code %d, got %d", http.StatusBadRequest, w.Code)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment