From 1e43f2a59bba0462494066767fac140601791718 Mon Sep 17 00:00:00 2001 From: mihna123 Date: Sun, 23 Aug 2026 17:47:16 +0200 Subject: listing: implement a service layer stub along with tests --- internal/listing/service_test.go | 89 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 internal/listing/service_test.go (limited to 'internal/listing/service_test.go') 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") + } +} -- cgit v1.3.1