Skip to content

Instantly share code, notes, and snippets.

@BK1031
Created July 16, 2024 09:06
Show Gist options
  • Save BK1031/7f29b028b8c4d45aa0473ca81ce489b6 to your computer and use it in GitHub Desktop.
Save BK1031/7f29b028b8c4d45aa0473ca81ce489b6 to your computer and use it in GitHub Desktop.
singlestore-go-bookstore TestCreateOrder
func TestCreateOrder(t *testing.T) {
ResetOrderTable()
ResetBookTable()
// Arrange
gatsby, _ := CreateBook(model.Book{
Title: "The Great Gatsby",
Author: "F. Scott Fitzgerald",
Price: 29.99,
Genre: "Fiction",
})
t.Run("Success", func(t *testing.T) {
// Act
order, _ := CreateOrder(model.Order{
Items: []model.OrderItem{
{
BookID: gatsby.ID,
Quantity: 2,
},
},
})
// Assert
if order.ID == 0 {
t.Errorf("Expected order ID to be non-zero, got %d", order.ID)
}
if order.Items[0].BookID != gatsby.ID {
t.Errorf("Expected order item book ID to be %d, got %d", gatsby.ID, order.Items[0].BookID)
} else if order.Items[0].Book.Title != gatsby.Title {
t.Errorf("Expected order item book title to be %s, got %s", gatsby.Title, order.Items[0].Book.Title)
} else if order.Total != gatsby.Price*2 {
t.Errorf("Expected order total to be %f, got %f", gatsby.Price, order.Total)
} else if order.CreatedAt.IsZero() {
t.Errorf("Expected order created at to be non-zero, got %v", order.CreatedAt)
}
})
t.Run("Book Not Found", func(t *testing.T) {
// Act
_, err := CreateOrder(model.Order{
Items: []model.OrderItem{
{
BookID: 999,
Quantity: 2,
},
},
})
// Assert
if err == nil {
t.Errorf("Expected error, got nil")
}
})
t.Run("InvalidQuantity", func(t *testing.T) {
// Act
_, err := CreateOrder(model.Order{
Items: []model.OrderItem{
{
BookID: gatsby.ID,
Quantity: 0,
},
},
})
// Assert
if err == nil {
t.Errorf("Expected error, got nil")
}
})
t.Run("EmptyItems", func(t *testing.T) {
// Act
_, err := CreateOrder(model.Order{
Items: []model.OrderItem{},
})
// Assert
if err == nil {
t.Errorf("Expected error, got nil")
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment