summaryrefslogtreecommitdiff
path: root/internal/listing/service_test.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/listing/service_test.go')
-rw-r--r--internal/listing/service_test.go89
1 files changed, 89 insertions, 0 deletions
diff --git a/internal/listing/service_test.go b/internal/listing/service_test.go
new file mode 100644
index 0000000..1d555c9
--- /dev/null
+++ b/internal/listing/service_test.go
@@ -0,0 +1,89 @@
+package listing
+
+import (
+ "errors"
+ "log/slog"
+ "os"
+ "slices"
+ "testing"
+)
+
+func TestMain(m *testing.M) {
+ slog.SetDefault(slog.New(slog.DiscardHandler))
+ os.Exit(m.Run())
+}
+
+func TestGetAll(t *testing.T) {
+ mock := NewRepositoryMock()
+ s := New(mock)
+ listings, err := s.GetAll()
+ if err != nil {
+ t.Error(err.Error())
+ }
+
+ if len(listings) != 3 {
+ t.Errorf("Listings lengths don't match. Have %d, want 3",
+ len(listings))
+ }
+}
+
+func TestGetAllWithError(t *testing.T) {
+ mock := &RepositoryMock{err: errors.New("db exploded")}
+ s := New(mock)
+ listings, err := s.GetAll()
+
+ if err == nil {
+ t.Error("No error returned from faulty GetAll call")
+ }
+
+ if listings != nil {
+ t.Error("Listings not nil when returned from faulty GetAll call")
+ }
+}
+
+func TestGetByCategory(t *testing.T) {
+ mock := NewRepositoryMock()
+ s := New(mock)
+
+ listings, err := s.GetByCategory("audi")
+ if err != nil {
+ t.Error(err.Error())
+ }
+
+ if len(listings) != 1 {
+ t.Errorf("Listings by category have wrong length. Have %d, want %d",
+ len(listings), 1)
+ }
+ if !slices.Contains(listings[0].category, "audi") {
+ t.Errorf("Returned listing has wrong category. Have %s, want audi",
+ listings[0].category)
+ }
+}
+
+func TestGetByCategoryNoMatches(t *testing.T) {
+ mock := &RepositoryMock{}
+ s := New(mock)
+
+ listings, err := s.GetByCategory("nonexistantcategory")
+ if err != nil {
+ t.Error(err.Error())
+ }
+
+ if listings != nil {
+ t.Error("Listings should be nil if no category matches")
+ }
+}
+
+func TestGetByCategoryWithError(t *testing.T) {
+ mock := &RepositoryMock{err: errors.New("datacenter hit by asteroid")}
+ s := New(mock)
+
+ listings, err := s.GetByCategory("mercedes")
+ if err == nil {
+ t.Error("Error nil when GetByCategory failed")
+ }
+
+ if listings != nil {
+ t.Error("Listings not nil when GetByCategory failed")
+ }
+}